-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathShortestsubsequence.cpp
94 lines (68 loc) · 1.29 KB
/
Shortestsubsequence.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
Name: Mehul Chaturvedi
IIT-Guwahati
*/
/*
Gary has two string S and V. Now Gary wants to know the length shortest subsequence in S such that it is not a subsequence in V.
Note: input data will be such so there will always be a solution.
Input Format :
Line 1 : String S of length N (1 <= N <= 1000)
Line 2 : String V of length M (1 <= M <= 1000)
Output Format :
Length of shortest subsequence in S such that it is not a subsequence in V
Sample Input :
babab
babba
Sample Output :
3
*/
#include <bits/stdc++.h>
using namespace std;
int solve(string s1,string s2)
{
int m =s1.size();
int n =s2.size();
vector<vector<int>> dp(m+1, vector<int>(n+1, 0));
for (int i = 0; i < n+1; ++i)
{
dp[m][i] = n-i;
}
for (int i = 0; i < m+1; ++i)
{
dp[i][n] = m-i;
}
for (int i = m-1; i >= 0; --i)
{
for (int j = n-1; j >= 0; --j)
{
int k = j;
while(k<s2.size())
{
if(s2[k]==s1[i])
{
break;
}
k++;
}
if (k==s2.size())
{
dp[i][j] = 1;
//return 1;
}
int c1 = 1+dp[i+1][k+1];
int c2 = dp[i+1][j];
dp[i][j] = min(c1, c2);
}
}
return dp[0][0];
}
int main( int argc , char ** argv )
{
ios_base::sync_with_stdio(false) ;
cin.tie(NULL) ;
string S,V;
cin>>S>>V;
cout<<solve(S,V)<<endl;
return 0;
return 0 ;
}