uva10405Longest Common Subsequence
题目:
求最大公共子序列(LCS)
分析:
用dp做,郁闷,还真有空格出现了,之前用scanf读入WA,改用gets读入A了
状态转移方程式为dp[i][j] = dp[i-1][j-1]+1, s1[i]==s2[j]
= max{dp[i-1][j],dp[i][j-1]} s1[i]!=s2[j]
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
#define X 1005
char s[X],ch[X];
int dp[X][X];
int main()
{
freopen("sum.in","r",stdin);
freopen("sum.out","w",stdout);
while(gets(s))
{
gets(ch);
////////////////////////////////////LCS模板
int len1 = strlen(s);
int len2 = strlen(ch);
memset(dp,0,sizeof(dp));
for(int i=1;i<=len1;i++)
for(int j=1;j<=len2;j++)
if(s[i-1]==ch[j-1])
dp[i][j] = dp[i-1][j-1]+1;
else
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
printf("%d\n",dp[len1][len2]);
}
return 0;
}