题目链接:
http://www.51nod.com/onlineJudge/submitDetail.html#!judgeId=215449
代码:
#include <iostream>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;
#define maxn 1005
int dp[maxn][maxn];
char s1[maxn],s2[maxn],s3[maxn];
int main()
{
while(scanf("%s%s",s1,s2)==2)
{
memset(dp,0,sizeof(dp));
int m=strlen(s1),n=strlen(s2);
///典型的动态规划
int k=0;
for(int i=0; i<m; i++)
{
for(int j=0; j<n; j++)
{
if(s1[i]==s2[j])
{
dp[i+1][j+1]=dp[i][j]+1;
}
else
dp[i+1][j+1]=max(dp[i][j+1],dp[i+1][j]);
}
}
int temp=dp[m][n];
s3[temp]='\0';
for(int i=m-1; i>=0; i--)
{
if(!temp)
break;
for(int j=n-1; j>=0; j--)
{
if(s1[i]==s2[j]&&dp[i+1][j+1]==temp)
{
s3[--temp]=s1[i];
break;
}
}
}
for(int i=0;i<strlen(s3);i++)
printf("%c",s3[i]);
printf("\n");
}
return 0;
}