最长公共子序列
输入
第1行:字符串A 第2行:字符串B (A,B的长度 <= 1000)
输出
输出最长的子序列,如果有多个,随意输出1个。
输入示例
abcicba abdkscab
输出示例
abca
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char s1[1010],s2[1010];
int dp[1111][1111];
int b[1111][1111];
int len1,len2;
void outpu(int x,int y)
{
if(x==0||y==0)
return ;
if(b[x][y]==0){
outpu(x-1,y-1);
printf("%c",s1[x-1]);
}
if(b[x][y]==1)
outpu(x,y-1);
if(b[x][y]==-1)
outpu(x-1,y);
}
int main()
{
scanf("%s%s",s1,s2);
len1=strlen(s1);
len2=strlen(s2);
memset(dp,0,sizeof(dp));
//int max=0;
for(int i=1;i<=len1;i++)
{
for(int j=1;j<=len2;j++)
{
if(s1[i-1]==s2[j-1]){
dp[i][j]=dp[i-1][j-1]+1;
b[i][j]=0;
}
else {
if(dp[i][j-1]>dp[i-1][j]){
dp[i][j]=dp[i][j-1];
b[i][j]=1;
}
else{
dp[i][j]=dp[i-1][j];
b[i][j]=-1;
}
}
}
}
outpu(len1,len2);
return 0;
}