//头文件
//LCSLength
//X[] 为X序列 Y[] 为Y序列
//c[i][j]存储Xi,Yj的最长公共子序列的长度
//b[i][j]记录c[i][j]的值是由哪一个子问题的截得到的
//c[i][j]= | 0; (i=0,j=0;)
//c[i][j]= | c[i-1][j-1]; (x[i]=y[j]) b[i][j]=1
//c[i][j]= | max{c[i][j-1],c[i-1][j]}; b[i][j]=2表示c[i][j]=c[i][j-1], b[i][j]=3表示c[i][j]=c[i-1][j]
template<int m,int n>//m为行数,n位列数
void LCSLength(char* x,char* y,int (&c)[m][n], int (&b)[m][n])
{
int row=m-1;
int colum=n-1;
c[0][0]=0;
for (int i=1;i<=row;i++)
{
c[i][0]=0;
}
for (int i=1;i<=colum;i++)
{
c[0][i]=0;
}
for (int i=1;i<=row;i++)
{
for (int j=1;j<=colum;j++)
{
if (x[i]==y[j])
{
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][j-1];
b[i][j]=2;
}
else
{
c[i][j]=c[i-1][j];
b[i][j]=3;
}
}
}
}
//主程序
// LCSLength.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include "LCSLength.h"
#include <string>
int _tmain(int argc, _TCHAR* argv[])
{
const int m=5,n=6;
char x[m+1]={' ','e','b','c','c','d'};
char y[n+1]={' ','g','b','c','f','r','c'};
int c[m+1][n+1] ={0};
int b[m+1][n+1] ={0};
LCSLength(x,y,c,b);
std::string strlcs="";
std::cout<<"最长公共子序列长度"<<c[m][n]<<std::endl;
int row=m,colum=n;
do
{
if (b[row][colum]==1)
{
strlcs=y[colum]+strlcs;
--row;
--colum;
}
else if (b[row][colum]==2)
{
--colum;
}
else
{
--row;
}
} while (row!=0&&colum!=0);
std::cout<<"公共子序列为"<<strlcs<<std::endl;
return 0;
}