最长子序列

趣味算法
//最长子序列
#include<bits/stdc++.h>
using namespace std;
int c[1002][1002],b[1002][1002];
char s1[1002],s2[1002];
int len1,len2;
void lcsl()
{
int i,j;
for(int i=1;i<=len1;i++)   //控制s1序列
 for(int j=1;j<=len2;j++)  //控制s2序列
 {
  if(s1[i-1]==s2[j-1])
  {
  c[i][j]=c[i-1][j-1]+1;
  b[i][j]=1;
 }
else
{
if(c[i][j-1]<c[i-1][j])
{
c[i][j]=c[i-1][j];
b[i][j]=3;}
if(c[i][j-1]>=c[i-1][j])
{
c[i][j]=c[i][j-1];
b[i][j]=2;}
}
 }
}
void print(int i,int j)
{
if(i==0||j==0) return;
if(b[i][j]==1)
{
print(i-1,j-1);
cout<<s1[i-1];
}
else if(b[i][j]==2)
print(i,j-1);
else print(i-1,j);
}
int main()          //正片开始
{
int i,j;
cin>>s1>>s2;
len1=strlen(s1);
len2=strlen(s2);
for(int i=1;i<=len1;i++)
c[i][0]=0;
for(int j=1;j<=len2;j++)
c[0][j]=0;
lcsl();
cout<<c[len1][len2];
print(len1,len2);
return 0;
}
posted @ 2021-02-17 21:10  -Sky-  阅读(37)  评论(0编辑  收藏  举报