題目大意:
給定兩個字符串序列,輸出其中包含的最長的子序列的長度。
輸入的兩個對比的字符串以若干空格分割(這就涉及到了讀入兩個字符串的技巧)
輸出:最長公共子序列的長度
LCS問題,經典的動態規劃問題
從c[i][j]={0 //當i=0或者j=0;
c[i-1][j-1]+1 //當 i,j>0 並且xi=yj;
max{c[i[-][j],c[i][j-1]} //當i,j>0 並且 xi與yj不等}
代碼如下:
# include <iostream>
using namespace std;
char s1[1000];
char s2[1000];
int c[1001][1001];
int main()
{
/*char s1[1000];
char s2[1000];
int c[1001][1001];*/
while(scanf("%s",s1+1)!=EOF)
{
scanf("%s",s2+1);
memset(c,0,sizeof(c));
int n,m,i,j,k;
n=strlen(s1+1);
m=strlen(s2+1);
for(i=1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
if(s1[i]==s2[j])
{
c[i][j]=c[i-1][j-1]+1;
}
else
{
if (c[i-1][j]>c[i][j-1])
c[i][j]=c[i-1][j];
else
c[i][j]=c[i][j-1];
}
}
}
printf("%d\n",c[n][m]);
}
return 0;
}