非连续最长公共子序列。参考王晓东《计算机算法设计与分析》P56~P59
#include<iostream>
using namespace std;
void LCSLength(char *x,char *y,int c[10][10],int b[10][10])
{
for(int i=0;i<strlen(x);i++)c[i][0]=0;
for(int j=0;j<strlen(y);j++)c[0][j]=0;
for(int i=0;i<strlen(x);i++)
{
for(int j=0;j<strlen(y);j++)
{
if(i==0||j==0)//下标为1的情况
{
if(x[i]==y[j])
{
c[i][j]=1;b[i][j]=1;
}
else
c[i][j] = 0;
}
else
{
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;
}
}
}
}
}
void LCS(int i,int j,char *x,int b[10][10])
{
if(i==0||j==0)//下标为1的情况
{
if(b[i][j]==1){cout<<x[i];return;}
else 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()
{
char x[10],y[10];int c[10][10],b[10][10];
while(cin>>x>>y)
{
LCSLength(x,y,c,b);
LCS(strlen(x)-1,strlen(y)-1,x,b);
cout<<endl;
}
}