#include <iostream>
#include <errno.h>
using namespace std;
#define X_LEN 7
#define Y_LEN 6
#define EQUAL 0
#define UP 1
#define LEVEL 2
void lcs_length(char *X, char *Y, int c[X_LEN+1][Y_LEN+1], int b[X_LEN+1][Y_LEN+1]);
void print_lcs(int b[X_LEN+1][Y_LEN+1], char *X, int i, int j);
int main()
{
char X[X_LEN+1] = {' ','A','B','C','B','D','A','B'};
char Y[Y_LEN+1] = {' ','B','D','C','A','B','A'};
int c[X_LEN+1][Y_LEN+1];
int b[X_LEN+1][Y_LEN+1];
int i,j;
lcs_length(X, Y, c, b);
for(i = 0; i <= X_LEN; i++)
{
for(j = 0; j <= Y_LEN; j++)
cout<<c[i][j]<<" ";
cout<<endl;
}
cout<<"The length of LCS is: "<<c[X_LEN][Y_LEN]<<endl;
cout<<"The longest common subsequence between X and Y is: "<<endl;
print_lcs(b, X, X_LEN, Y_LEN);
cout<<endl;
return 0;
}
void lcs_length(char *X, char *Y, int c[X_LEN+1][Y_LEN+1], int b[X_LEN+1][Y_LEN+1])
{
int i,j;
for(i = 0; i <= X_LEN; i++)
c[i][0] = 0;
for(j = 0; j <= Y_LEN; j++)
c[0][j] = 0;
/* if(x[i] == y[j])
c[i][j] = c[i-1][j-1]+1; b [i][j] = EQUAL;
else if(up > left)
c[i][j] = up; b[i][j] = UP;
else c[i][j] = left; b[i][j] = LEFT;
*/
for(i = 1; i <= X_LEN; i++)
{
for(j = 1; j <= Y_LEN; j++)
{
if(X[i] == Y[j])
{
c[i][j] = c[i][j] + 1;
b[i][j] = EQUAL;
}
else if(c[i-1][j] >= c[i][j-1])
{
c[i][j] = c[i-1][j];
b[i][j] = UP;
}
else
{
c[i][j] = c[i][j-1];
b[i][j] = LEVEL;
}
}
}
}
void print_lcs(int b[X_LEN+1][Y_LEN+1],char * X,int i,int j)
{
if(i == 0 || j == 0)
return;
if(b[i][j] == EQUAL)
{
print_lcs(b, X, i-1, j-1);
putchar(X[i]);
}
else if(b[i][j] == UP)
{
print_lcs(b, X, i-1, j);
}
else
print_lcs(b, X, i, j-1);
}
算法导论之动态规划:最长公共子序列
最新推荐文章于 2024-04-29 21:11:51 发布