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
   | #include <bits/stdc++.h> using namespace std; vector<vector<int> > choice; string path; int lcs(string& s1, string& s2, int m, int n) {     vector<vector<int> > dp(m+1, vector<int>(n+1, 0));     choice.resize(m+1, vector<int>(n+1));          for(int i = 1; i <= m; i++) {         for(int j = 1; j <= n; j++) {             if(s1[i-1] == s2[j-1]) {                 dp[i][j] = dp[i-1][j-1] + 1;                 choice[i][j] = 1;             } else if(dp[i-1][j] >= dp[i][j-1]) {                 dp[i][j] = dp[i-1][j];                 choice[i][j] = 2;             } else {                 dp[i][j] = dp[i][j-1];                 choice[i][j] = 3;             }         }     }          return dp[m][n]; }
  void findPath(vector<vector<int> >& choice, string& s, int i, int j) {     if(i==0 || j==0) return;
      if(choice[i][j] == 1){         findPath(choice, s, i-1, j-1);         path.push_back(s[i-1]);     } else if(choice[i][j] == 2) {         findPath(choice, s, i-1, j);     } else {         findPath(choice, s, i, j-1);     } }
  int main() {     string s1 = "gbabcdef", s2 = "gaczef";          int m = s1.size();     int n = s2.size();     int x = lcs(s1, s2, m, n);     printf("length of lcs: %d\n", x);          findPath(choice, s1, m, n);     cout << "lsc: " << path << "\n";     system("pause");     return 0; }
 
   |