HDU 1159 - Common Subsequence [最长公共子序列]
动规简单题,dp[i][j]表示的状态为字符串a.substr(0, i)和b.substr(0, j)的最长公共子序列。
#include <iostream> #include <cstdio> #include <cstring> #include <string> using namespace std; int dp[1024][1024]; int main() { string a, b; while(cin >> a >> b){ memset(dp, 0, sizeof(dp)); for(int i = 1; i <= a.size(); ++i){ for(int j = 0; j <= b.size(); ++j){ if(a[i-1] == b[j-1]) dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } cout << dp[a.size()][b.size()] << endl; } return 0; }