/* Memoizing the solutioni of subseq3.cpp, using a two-dimensional vector which works on the indices of the two strings. */ #include #include #include #include #include using namespace std; class Subseq { public: string s1, s2; vector < vector > cache; // Here's our memoization cache. int MCS(size_t i1, size_t i2); }; int Subseq::MCS(size_t i1, size_t i2) { int r1, r2; size_t i; /* Base case. */ if (s1.size() == i1 || s2.size() == i2) return 0; /* Create the cache if necessary -- sentinelize with -1. */ if (cache.size() == 0) { cache.resize(s1.size()); for (i = 0; i < s1.size(); i++) cache[i].resize(s2.size(), -1); } /* If the answer is in the cache, return it. */ if (cache[i1][i2] != -1) return cache[i1][i2]; /* Otherwise, calculate it with recursion. */ if (s1[i1] == s2[i2]) { cache[i1][i2] = 1 + MCS(i1+1, i2+1); } else { r1 = MCS(i1, i2+1); r2 = MCS(i1+1, i2); cache[i1][i2] = (r1 > r2) ? r1 : r2; } return cache[i1][i2]; } 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(0, 0) << endl; return 0; }