Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // shortest common supersequence
- // [1 ,2 ,3, 4]
- // subsequnce (order matters but maybe not continuous)
- // substring or subarray .. (need to be contigous)
- // subset same as subsequence ..
- int solve(string s1 , string s2){
- int sa = s1.length();
- int sb = s2.length();
- vector<vector<int>> dp (sa+1 ,vector<int>(sb+1,0));
- // a represents the ath element .. b represents the knapsack present
- for(int a=1;a<=sa;a++){
- for(int b=1;b<=sb;b++){
- if(s1[a-1] == s2[b-1]){
- dp[a][b] = 1 + dp[a-1][b-1]; //here we can choose ith element again
- }else{
- dp[a][b] = max(dp[a-1][b] , dp[a][b-1]); // cant choose the ath element becuase its weight is more
- }
- }
- }
- // to print the scs
- int i = sa;
- int j = sb;
- string res = "";
- while(i>0 && j>0){
- if(s1[i-1] == s2[j-1] ){
- res+=s1[i-1];
- i--;
- j--;
- }else{
- if(dp[i-1][j] > dp[i][j-1]){
- res += s1[i-1];
- i--;
- }else{
- res+=s2[j-1];
- j--;
- }
- }
- }
- while(i>0){
- res+=s1[i-1];
- i--;
- }
- while(j>0){
- res+=s2[j-1];
- j--;
- }
- reverse(res.begin(),res.end()); /////// reversing the string is very important
- cout << res <<"\n";
- int ans =0;// gives to length of lcs
- int lcs = dp[sa][sb];
- ans = sa+sb-lcs;
- return ans;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement