问题描述:
给定两个序列s1,s2,求二者的最长公共子序列长度
例如:
algorithms
alchemist
输出:5
即alhms
#include<iostream>
#include<cstring>
using namespace std;
int f[1010][1010];
string s1;
string s2;
void ans(int i,int j)
{
if(i==0||j==0)
{
return;
}
if(s1[i-1]==s2[j-1])
{
ans(i-1,j-1);
cout<<s1[i-1];
}
else if(f[i-1][j]>f[i][j-1])
{
ans(i-1,j);
}
else ans(i,j-1);
}
int main()
{
cin>>s1>>s2;
int n=s1.size() ;
int m=s2.size() ;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(s1[i-1]==s2[j-1])
{
f[i][j]=1+f[i-1][j-1];
}
else
{
f[i][j]=max(f[i-1][j],f[i][j-1]);
}
}
}
cout<<f[n][m]<<endl;
ans(n,m);
return 0;
}