#include <stdio.h>
char a[] = {'\0','a','b','c','b','d','a','b'};
#define a_len 7
char b[] = {'\0','b','d','c','a','b','a'};
#define b_len 6
int c[a_len+1][b_len+1];
int p[a_len+1][b_len+1];
#define UPLEFT 3
#define UP 2
#define LEFT 1
void lcs_length(char a[], int alength, char b[], int blength)
{
int i = 0;
for (i = 0; i <= alength; i++)
{
c[i][0] = 0;
}
for (i = 0; i<= blength; i++)
{
c[0][i] = 0;
}
int j = 0;
for (i = 1; i <= alength; i++)
{
for (j = 1; j<= blength; j++)
{
if (a[i] == b[j])
{
c[i][j] = c[i-1][j-1] + 1;
p[i][j] = UPLEFT;
}
else
{
if (c[i-1][j] >= c[i][j-1])
{
c[i][j] = c[i-1][j];
p[i][j] = UP;
}
else
{
c[i][j] = c[i][j-1];
p[i][j] = LEFT;
}
}
}
}
}
void print_lcs(char a[], int a_start, int a_end, char b[], int b_start, int b_end)
{
if (a_end < a_start || b_end < b_start)
{
return;
}
if (p[a_end][b_end] == UPLEFT)
{
print_lcs(a, a_start, a_end - 1, b, b_start, b_end - 1);
printf("%c", a[a_end]);
}
else if (p[a_end][b_end] == UP)
{
print_lcs(a, a_start, a_end-1, b, b_start, b_end);
}
else
{
print_lcs(a, a_start, a_end, b, b_start, b_end-1);
}
}
int main()
{
lcs_length(a, a_len, b, b_len);
print_lcs(a, 1, a_len, b, 1, b_len);
return 1;
}
|