#include #include #include #include #include using namespace std; class Subseq { public: string s1, s2; vector < vector > cache; int MCS(); }; int Subseq::MCS() { int r1, r2, i1, i2; size_t i; /* Create the cache, and fill it with zero's. You'll note that cache[i][s2.size()] and cache[s1.size()][i] should equal zero, so we don't have to calculate them. */ cache.resize(s1.size()+1); for (i = 0; i < cache.size(); i++) cache[i].resize(s2.size()+1, 0); /* Now start with i1 and i2 being s1.size()-1 and s2.size()-1 respectively, and fill in the cache from high to low. */ for (i1 = (int) s1.size()-1; i1 >= 0; i1--) { for (i2 = (int) s2.size()-1; i2 >= 0; i2--) { if (s1[i1] == s2[i2]) { cache[i1][i2] = 1 + cache[i1+1][i2+1]; } else { r1 = cache[i1][i2+1]; r2 = cache[i1+1][i2]; cache[i1][i2] = (r1 > r2) ? r1 : r2; } } } /* The final answer is in cache[0][0]. */ return cache[0][0]; } int main(int argc, char **argv) { Subseq ss; if (argc != 3) { cerr << "usage: subseq s1 s2\n"; exit(1); } ss.s1 = argv[1]; ss.s2 = argv[2]; cout << ss.MCS() << endl; return 0; }