最長公共子序列
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
string str;
char s1[1000], s2[1000];
int dp[1000][1000], mark[1000][1000];///數據太大,dp數組變成滾動數組
int LCS()
{
int i, j, n, m;
memset(dp,0,sizeof(dp));
n = strlen(s1);
m = strlen(s2);
for(i = 0; i <= n; i++)
mark[i][0] = 1;
for(i = 0; i <= m; i++)
mark[0][i] = -1;
for(i = 1; i <= n; i++)
{
for(j = 1; j <= m; j++)
{
if(s1[i-1] == s2[j-1])
{
dp[i][j] = dp[i-1][j-1] + 1;
mark[i][j] = 0;
}
else if(dp[i-1][j] >= dp[i][j-1])
{
dp[i][j] = dp[i-1][j];
mark[i][j] = 1;
}
else
{
dp[i][j] = dp[i][j-1];
mark[i][j] = -1;
}
}
}
return dp[n][m];
}
void SameLCS(int i,int j)///mark[i][j] == 1表示s1序列的,mark[i][j] == -1表示s2序列的
{
if(!i && !j)
return ;
if(mark[i][j] == 0)///公共序列
{
SameLCS(i-1,j-1);
str += s1[i-1];
}
else if(mark[i][j] == 1)
SameLCS(i-1,j);
else
SameLCS(i,j-1);
}
int main()
{
while(~scanf("%s %s",s1,s2))
{
int ans, len1, len2;
len1 = strlen(s1);
len2 = strlen(s2);
ans = LCS();
printf("%d\n",ans);
SameLCS(len1,len2);
cout << str << endl;
}
return 0;
}