版权声明:@ly https://blog.csdn.net/lytwy123/article/details/83049696
#include<iostream>
#include<cstdio>
using namespace std;
char x[101]; //字符数组x存储字符串x
char y[101]; //字符数组y存储字符串y
int b[101][101]; //记录c[i][j]怎么来的,以及输出子序列元素
int c[101][101]; //记录 X和Y的最长子序列长度
//快速的求出c数组与b数组的值
void LCSLength(int m,int n,char *x,char *y,int c[][101],int b[][101])
{
int i,j;
for(i = 1;i<=m;i++) c[i][0] = 0;
for(i = 1;i<=n;i++) c[0][i] = 0;
for(i = 1;i<=m;i++){
for(j = 1;j<=n;j++){
if(x[i] == y[j]){
c[i][j] = c[i-1][j-1]+1;
b[i][j] = 1;
}
else if(c[i-1][j] >= c[i][j-1]){
c[i][j] = c[i-1][j];
b[i][j] = 2;
}
else
{
c[i][j] = c[i][j-1];
b[i][j] = 3;
}
}
}
}
//回溯b数组求出哪些字符是相同的
void LCS(int i,int j,char *x,int b[][101])
{
if(i==0 || j==0) return;
if(b[i][j] == 1){
LCS(i-1,j-1,x,b);
cout<<x[i];
}
else if(b[i][j] == 2)
LCS(i-1,j,x,b);
else
LCS(i,j-1,x,b);
}
int main()
{
int m,n;
cin>>m>>n;
cout<<"please input char x:"<<endl;
for(int i = 1;i<=m;i++) cin>>x[i];
cout<<"please input char y:"<<endl;
for(int j = 1;j<=n;j++) cin>>y[j];
LCSLength(m,n,x,y,c,b);
cout<<"最长公共子序列:"<<endl;
LCS(m,n,x,b);
cout<<endl;
cout<<"最长公共子序列长度:"<<endl;
cout<<c[m][n];
return 0;
}