Advertisement
zunayeds

DS_E3_C

May 30th, 2015
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. #include<iostream>
  2. #include<string>
  3. using namespace std;
  4.  
  5. int LCS(const string& str1, const string& str2) {
  6.      if(str1.empty() || str2.empty()) {
  7.           return 0;
  8.      }
  9.  
  10.      int *curr = new int [str2.size()];
  11.      int *prev = new int [str2.size()];
  12.      int *swap = nullptr;
  13.      int maxSubstr = 0;
  14.  
  15.      for(int i = 0; i<str1.size(); ++i) {
  16.           for(int j = 0; j<str2.size(); ++j) {
  17.                if(str1[i] != str2[j]) {
  18.                     curr[j] = 0;
  19.                }
  20.                else {
  21.                     if(i == 0 || j == 0) {
  22.                          curr[j] = 1;
  23.                     }
  24.                     else {
  25.                          curr[j] = 1 + prev[j-1];
  26.                     }
  27.  
  28.                     if(maxSubstr < curr[j]) {
  29.                          maxSubstr = curr[j];
  30.                     }
  31.                }
  32.           }
  33.           swap=curr;
  34.           curr=prev;
  35.           prev=swap;
  36.      }
  37.      delete [] curr;
  38.      delete [] prev;
  39.      return maxSubstr;
  40. }
  41.  
  42. int main() {
  43.     int n;
  44.     cin >> n;
  45.     string x, y;
  46.     for (int i = 1; i <= n; i++) {
  47.         cin >> x >> y;
  48.         cout << "Case " << i << ": "  << LCS(x, y) << endl;
  49.     }
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement