最长公共子序列,动规经典题
f[i][j] = max {f[i-1][j], f[i][j-1], f[i-1][j-1]+(s1[i] == s2[j])}
#include <iostream> #include <string> using namespace std; const int maxn = 1010; int f[maxn][maxn]; inline int max(int x, int y, int z) { if (x > y) return x > z ? x : z; else return y > z ? y : z; } int main() { string s1, s2; int i, j; while (cin >> s1 >> s2) { int len1 = s1.size(); int len2 = s2.size(); for (i = 0; i <= len2; i++) f[0][i] = 0; for (i = 0; i <= len1; i++) f[i][0] = 0; for (i = 1; i <= len1; i++) { for (j = 1; j <= len2; j++) { bool tmp = (s1[i-1] == s2[j-1]); f[i][j] = max(f[i-1][j], f[i][j-1], f[i-1][j-1]+tmp); } } cout << f[len1][len2] << endl; } return 0; }