jayati

Shortest Common Supersequence

Nov 13th, 2023
683
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. //{ Driver Code Starts
  2. //Initial template for C++
  3.  
  4. #include<bits/stdc++.h>
  5. using namespace std;
  6.  
  7.  
  8. // } Driver Code Ends
  9. //User function template for C++
  10. //User function template for C++
  11.  
  12.  
  13. class Solution
  14. {
  15.     public:
  16.     //Function to find length of shortest common supersequence of two strings.
  17.     int shortestCommonSupersequence(string X, string Y, int m, int n)
  18.     {
  19.          vector<vector<int>> dp(m+1, vector<int>(n+1, 0));
  20.        
  21.         for(int i = 0; i < m; i++){
  22.             for(int j = 0; j < n; j++){
  23.                 if(X[i] == Y[j])    dp[i+1][j+1] = dp[i][j] + 1;
  24.                 else    dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]);
  25.             }
  26.         }
  27.        
  28.         return (m+n-dp[m][n]);
  29.        
  30.     }
  31. };
  32.  
  33. //{ Driver Code Starts.
  34.  
  35. int main()
  36. {  
  37.    
  38.     int t;
  39.    
  40.     //taking total testcases
  41.     cin >> t;
  42.     while(t--){
  43.     string X, Y;
  44.     //taking String X and Y
  45.     cin >> X >> Y;
  46.    
  47.     //calling function shortestCommonSupersequence()
  48.     Solution obj;
  49.     cout << obj.shortestCommonSupersequence(X, Y, X.size(), Y.size())<< endl;
  50.     }
  51.     return 0;
  52. }
  53.  
  54.  
  55. // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment