fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. using namespace std;
  4.  
  5. int main() {
  6. string x, y;
  7. cin >> x >> y;
  8. int L[x.length()+1][y.length()+1];
  9.  
  10. // Initialize first row and column
  11. for (int i = 0; i <= x.length(); i++)
  12. L[i][0] = 0;
  13. for (int j = 0; j <= y.length(); j++)
  14. L[0][j] = 0;
  15.  
  16. // Fill table
  17. for (int i = 1; i <= x.length(); i++) {
  18. for (int j = 1; j <= y.length(); j++) {
  19. if (x[i-1] == y[j-1])
  20. L[i][j] = L[i-1][j-1] + 1;
  21. else
  22. L[i][j] = max(L[i-1][j], L[i][j-1]);
  23. }
  24. }
  25.  
  26. cout << "LCS length = " << L[x.length()][y.length()] << endl;
  27. }
  28.  
Success #stdin #stdout 0s 5320KB
stdin
ABA BBA
stdout
LCS length = 2