#include #include #include #include using namespace std; class Subseq { public: map cache; int MCS(const string &s1, const string &s2); }; int Subseq::MCS(const string &s1, const string &s2) { string key; // We'll turn the arguments into a string for the cache. int r1, r2; /* Take care of the base cases without worrying about the cache. */ if (s1.size() == 0 || s2.size() == 0) return 0; /* Create the memoization key, and check the cache. */ key = s1 + ":"; key += s2; if (cache.find(key) != cache.end()) return cache[key]; /* If it's not in the cache, then do the recursion and put the answer into the cache. */ if (s1[0] == s2[0]) { cache[key] = 1 + MCS(s1.substr(1), s2.substr(1)); } else { r1 = MCS(s1, s2.substr(1)); r2 = MCS(s1.substr(1), s2); cache[key] = (r1 > r2) ? r1 : r2; } return cache[key]; } int main(int argc, char **argv) { Subseq ss; string s1, s2; if (argc != 3) { cerr << "usage: subseq s1 s2\n"; exit(1); } s1 = argv[1]; s2 = argv[2]; cout << ss.MCS(s1, s2) << endl; return 0; }