最长公共子序列
#include <stdio.h>
#include <string.h>
void LCSLength(int m, int n, char x[20], char y[20], int c[30][30], int b[30][30]) {
int i, j;
for(i = 1; i <= m; i++) c[i][0] = 0;
for(i = 1; i <= n; i++) c[0][i] = 0;
for(i = 1; i <= m; i++)
for(j = 1; j <= n; j++)
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[20], int b[30][30]) {
if(i == 0 || j == 0) return ;
if(b[i][j] == 1) {
LCS(i - 1, j - 1, x, b);
printf("%c", 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[] = "abcdefghjhj", y[] = "abcdegd";
int n, m, b[30][30], c[30][30];
m = strlen(x); n = strlen(y);
LCSLength(m, n, x, y, c, b);
LCS(m, n, x, b);
return 0;
}
怎么不对啊!???????????
#include <string.h>
void LCSLength(int m, int n, char x[20], char y[20], int c[30][30], int b[30][30]) {
int i, j;
for(i = 1; i <= m; i++) c[i][0] = 0;
for(i = 1; i <= n; i++) c[0][i] = 0;
for(i = 1; i <= m; i++)
for(j = 1; j <= n; j++)
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[20], int b[30][30]) {
if(i == 0 || j == 0) return ;
if(b[i][j] == 1) {
LCS(i - 1, j - 1, x, b);
printf("%c", 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[] = "abcdefghjhj", y[] = "abcdegd";
int n, m, b[30][30], c[30][30];
m = strlen(x); n = strlen(y);
LCSLength(m, n, x, y, c, b);
LCS(m, n, x, b);
return 0;
}