动态规划法求解最长公共子序列问题
#include <iostream>
using namespace std;
#define M 8
#define N 7
char x[M]={0,'A','B','C','B','D','A','B'};
char y[N]={0,'B','D','C','A','B','A'};
int c[10][10],b[10][10];
void LCSLength()
{
for(int i=0;i<=M;i++) {c[i][0]=0;}
for(int j=1;j<=N;j++) {c[0][j]=0;}
for(int i=1;i<=M;i++)
{
for(int 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]=3;
}
else
{
c[i][j]=c[i][j-1];
b[i][j]=2;
}
}
}
}
void LCS(int i,int j)
{
if(i==0||j==0) return;
if(b[i][j]==1)
{
LCS(i-1,j-1);
cout<<x[i];
}
else if(b[i][j]==2)
{
LCS(i,j-1);
}
else
{
LCS(i-1,j);
}
}
int main()
{
LCSLength();
LCS(M,N);
return 0;
}