Common Subsequence
Time Limit:1000MS Memory Limit:10000K
最长公共子序列,注意状态方程的确立,在求dp的两个for循环中,逐次求出应有的解,注意状态转移过程,最后求出应有的解。
#include <iostream>
#include <string.h>
#include <memory.h>
using namespace std;
int dp[1000][1000];
char cat[1004],dog[1004];
int max(int a,int b,int c)
{
if(a >= b && a >= c) return a;
if(b >= a && b >= c) return b;
return c;
}
int same(int a,int b)
{
if(a == b) return 1;
return 0;
}
int main()
{
int t1,t2,i,j;
while(cin >> cat >> dog)
{
memset(dp,0,sizeof(dp));
t1 = strlen(cat);t2 = strlen(dog);
for(i = 1;i <= t1;i ++)
for(j = 1;j <= t2;j ++)
dp[i][j] = max(dp[i-1][j-1] + same(cat[i-1],dog[j-1]),dp[i-1][j],dp[i][j-1]);
cout << dp[t1][t2] << endl;
}
return 0;
}