mahmoud-a
8/28/2017 - 6:21 PM

https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1346

#include <bits/stdc++.h>

#define ll long long
#define sz(v) ((int) ((v).size()))
#define clr(v, d) memset(v, d, sizeof(v))
#define lp(i, n) for(int i = 0; i < (int)(n); ++i)
#define rep(i, v) for(int i = 0; i < sz(v); ++i)

using namespace std;

int n;
const int MAX = 1e3+5;
const int OO = 1e9;

string s1, s2;
int n1, n2;
int cache[MAX][MAX];

int lcs(int i, int j) {
    if(i == n1 || j == n2)
        return 0;

    int &ret = cache[i][j];
    if(ret != -1)
        return ret;
    int ch1 = -1*OO;
    if(s1[i] == s2[j])
        ch1 = 1+lcs(i+1, j+1);
    int ch2 = lcs(i, j+1);
    int ch3 = lcs(i+1, j);

    return ret = max(max(ch1, ch2), ch3);
}


int main() {
    while(getline(cin, s1) && getline(cin, s2)) {
        clr(cache, -1);
        n1 = s1.length();
        n2 = s2.length();
        cout << lcs(0, 0) << endl;
    }
    return 0;
}