#include<iostream>
#include<stdio.h>
#include<string.h>
#include<bits/stdc++.h>
#define MAXLEN 50
using namespace std;
void LCSlength(int m,int n,char *x,char *y,int c[][MAXLEN],int b[][MAXLEN])
{
for(int i=0;i<=m;i++)//m为字符个数
{
c[i][0]=0;
}
for(int i=1;i<=n;i++)
{
c[0][i]=0;
}
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(x[i-1]==y[j-1])//因为字符串是在从第0位开始存储的
{
c[i][j]=c[i-1][j-1]+1;
b[i][j]=1;//本算法采用1,2,3三个整形作为标记
}
else if(c[i-1][j]>=c[i][j-1])//这个else if关键
{
c[i][j]=c[i-1][j];
b[i][j]=2;
}
else
{
c[i][j]=c[i][j-1];
b[i][j]=3;
}
}
}
}
void LCS(int i,int j,char *x,int b[][MAXLEN])
{
if(i==0||j==0)
{
return;
}
if(b[i][j]==1)
{
LCS(i-1,j-1,x,b);
cout<<x[i-1]<<" ";
}
else if(b[i][j]==2)//这个else if 很关键
{
LCS(i-1,j,x,b);
}
else
{
LCS(i,j-1,x,b);
}
}
int main()
{
char x[MAXLEN] = {"*abcbdab"};
char y[MAXLEN] = {"*bdcdba"};
//传递二维数组必须知道列数,所以使用MAXLEN这个确定的数
int b[MAXLEN][MAXLEN];//b矩阵是用来存储这个问题是由那个子问题来解决的
int c[MAXLEN][MAXLEN];//c矩阵用来存储最长公共子串的长度
int m, n;
m = strlen(x);
// cout<<m<<endl;
n = strlen(y);
//cout<<n<<endl;
LCSlength(m,n,x,y,c,b);
cout<<"b矩阵是用来存储这个问题是由那个子问题来解决的"<<endl;
for(int i=0;i<=m;i++)
{
for(int j=0;j<=n;j++)
{
cout<<b[i][j];
}
cout<<endl;
}
cout<<"c矩阵用来存储最长公共子串的长度 "<<endl;
for(int i=0;i<=m;i++)
{
for(int j=0;j<=n;j++)
{
cout<<c[i][j];
}
cout<<endl;
}
LCS(m,n,x,b);
}