Advertisement
Oppenheimer

shortest common supersequence

Aug 14th, 2022 (edited)
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. // shortest common supersequence
  2. // [1 ,2 ,3, 4]
  3. // subsequnce (order matters but maybe not continuous)
  4. // substring or subarray .. (need to be contigous)
  5. // subset same as subsequence ..
  6. int solve(string s1 , string s2){
  7.     int sa = s1.length();
  8.     int sb = s2.length();
  9.     vector<vector<int>> dp (sa+1 ,vector<int>(sb+1,0));
  10.     // a represents the ath element .. b represents the knapsack present
  11.    
  12.     for(int a=1;a<=sa;a++){
  13.         for(int b=1;b<=sb;b++){
  14.             if(s1[a-1] == s2[b-1]){
  15.             dp[a][b] = 1 + dp[a-1][b-1]; //here we can choose ith element again
  16.             }else{
  17.             dp[a][b] = max(dp[a-1][b] , dp[a][b-1]); // cant choose the ath element becuase its weight is more
  18.             }
  19.         }
  20.     }
  21.    
  22.     // to print the scs
  23.     int i = sa;
  24.     int j = sb;
  25.     string res = "";
  26.     while(i>0 && j>0){
  27.         if(s1[i-1] == s2[j-1] ){
  28.             res+=s1[i-1];
  29.             i--;
  30.             j--;
  31.         }else{
  32.          if(dp[i-1][j] > dp[i][j-1]){
  33.             res += s1[i-1];
  34.              i--;
  35.          }else{
  36.             res+=s2[j-1];
  37.              j--;
  38.          }
  39.            
  40.        
  41.         }
  42.     }
  43.    
  44.     while(i>0){
  45.         res+=s1[i-1];
  46.         i--;
  47.     }
  48.     while(j>0){
  49.         res+=s2[j-1];
  50.         j--;
  51.     }
  52.    
  53.     reverse(res.begin(),res.end()); /////// reversing the string is very important
  54.     cout << res <<"\n";
  55.    
  56.    
  57.    
  58.    
  59.     int ans =0;// gives to length of lcs
  60.     int lcs = dp[sa][sb];
  61.     ans = sa+sb-lcs;
  62.     return ans;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement