#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int lcsLength(int **c,char *x,char *y,int i,int j)
{
if(i<0 || j<0)
return -1;
if(c[i][j] != -1)
return c[i][j];
if(x[i-1]==y[j-1])
{
int a=lcsLength(c,x,y,i-1,j-1);
c[i][j]=a+1;
}
else
{
int up=lcsLength(c,x,y,i-1,j);
int left=lcsLength(c,x,y,i,j-1);
if(up>=left)
c[i][j]=up;
else
c[i][j]=left;
}
return c[i][j];
}
int** initC(char *x,char *y)
{
int xlen=strlen(x);
int ylen=strlen(y);
int **c=(int**)malloc((xlen+1)*sizeof(int*));
for(int i=0;i<xlen+1;i++)
{
c[i]=(int*)malloc((ylen+1)*sizeof(int));
}
for(int i=0;i<xlen+1;i++)
for(int j=0;j<ylen+1;j++)
c[i][j]=-1;
for(int i=0;i<xlen+1;i++)
c[i][0]=0;
for(int j=0;j<ylen+1;j++)
c[0][j]=0;
return c;
}
void printLCS(int **c,char *x,char *y)
{
int xlen=strlen(x);
int ylen=strlen(y);
int i=xlen,j=ylen;
char *s=(char*)malloc((xlen)*sizeof(char));
while(i>=1 && j>=1)
{
if(x[i-1]==y[j-1])
{
s[i-1]=x[i-1];
i--;
j--;
}
else if(c[i][j]==c[i-1][j])
{
s[i-1]='*';
i--;
}
else
j--;
}
for(;i<xlen;i++)
{
if(s[i]!='*')
printf("%c ",s[i]);
}
printf("\n");
}
void printC(int **c,int xlen,int ylen)
{
for(int i=1;i<xlen+1;i++)
{
for(int j=1;j<ylen+1;j++)
{
if(c[i][j]==-1)
printf("%d ",c[i][j]);
else
printf("%d ",c[i][j]);
}
printf("\n");
}
}
void main()
{
char *x="ABCBDAB";
char *y="BDCABA";
int **c=initC(x,y);
lcsLength(c,x,y,strlen(x),strlen(y));
printLCS(c,x,y);
//printC(c,strlen(x),strlen(y));
getchar();
}
算法导论 练习题 15.4-3
最新推荐文章于 2020-11-19 10:59:39 发布