#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
int c[MAXSIZE][MAXSIZE];
int flag[MAXSIZE][MAXSIZE];
int a[MAXSIZE] = {1,2,3,2,4,1,2,5};
int b[MAXSIZE] = {2,4,3,1,2,1,5};
//递归找最长公共子序列长度
int find_longest(int asize,int bsize)
{
int onenum,twonum;
if(asize==0 || bsize == 0)
{
return 0;
}
else
{
if(a[asize-1]==b[bsize-1])
{
flag[asize][bsize]=1;
c[asize][bsize] = c[asize-1][bsize-1]+1;
return 1+find_longest(asize-1,bsize-1);
}
else
{
onenum = find_longest(asize-1,bsize);
twonum = find_longest(asize,bsize-1);
if(onenum>twonum)
{
c[asize][bsize] = onenum;
flag[asize][bsize] = 2;
return onenum;
}
else
{
c[asize][bsize] = twonum;
flag[asize][bsize] = 3;
return twonum;
}
}
}
}
//动态规划寻找最长公共子序列长度
void dynamic_longest(int asize,int bsize)
{
int i,j;
for(i=1;i<=asize;i++)
{
for(j=1;j<=bsize;j++)
{
if(a[i-1]==b[j-1])
{
c[i][j] = c[i-1][j-1]+1;
flag[i][j]=1;
}
else if(c[i-1][j]>=c[i][j-1])
{
c[i][j] = c[i-1][j];
flag[i][j] = 2;
}
else
{
c[i][j] = c[i][j-1];
flag[i][j]=3;
}
}
}
}
void find_more(int i,int j)
{
if(i==0 || j==0)
{
return ;
}
if(flag[i][j] ==1)
{
find_more(i-1,j-1);
printf("%d",a[i-1]);
}
else if(flag[i][j]==2)
{
find_more(i-1,j);
}
else
{
find_more(i,j-1);
}
}
int main()
{
int i,j;
int count=0;
for(i=0;i<=MAXSIZE;i++)
{
for(j=0;j<=MAXSIZE;j++)
{
c[i][j] = 0;
flag[i][j] = 0;
}
}
//count = find_longest(8,7);
//printf("count=%d\n",count);
dynamic_longest(8,7);
printf("count = %d\n",c[8][7]);
printf("--------------------------\n");
for(i=0;i<=MAXSIZE;i++)
{
for(j=0;j<=MAXSIZE;j++)
{
printf("%5d",c[i][j]);
}
printf("\n");
}
printf("----------------\n");
for(i=0;i<=MAXSIZE;i++)
{
for(j=0;j<=MAXSIZE;j++)
{
printf("%5d",flag[i][j]);
}
printf("\n");
}
find_more(8,7);
}