原题链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1159
状态转移方程:
if (s1[ i-1 ] == s2[ j-1 ])
dp[i][j] = dp[ i - 1 ][ j - 1 ] + 1;
else
dp[i][j] = dp[ i ][j - 1]>dp[ i-1 ][ j ] ? dp[ i ][j - 1] : dp[ i-1 ][ j ];
比较好理解。
代码如下:
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
const int N = 1000 + 10;
int dp[N][N];
int main()
{
string s1, s2;
while (cin >> s1 >> s2)
{
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= s1.length(); i++)
{
for (int j = 1; j <= s2.length(); j++)
{
if (s1[i-1] == s2[j-1])
dp[i][j] = dp[i - 1][j - 1] + 1;
else dp[i][j] = dp[i][j - 1]>dp[i-1][j] ? dp[i][j - 1] : dp[ i-1 ][j];
}
}
cout << dp[s1.length()][s2.length()] << endl;
}
return 0;
}