#include <cstdio>
#include <string.h>
#include <string>
char x[100];
char y[100];
int c[100][100];
int b[100][100];
int m,n;
void LCSLength(char x[],char y[],int c[100][100],int b[100][100],int m,int n){
for(int i = 1;i <= m; i++) c[i][0] = 0;
for(int i = 1;i <= n; i++) c[0][i] = 0;
for(int i = 1;i <= m; i++){
for(int j = 1;j <= n; j++){
if(x[i] == y[j]) {
c[i][j] = c[i-1][j-1] +1;
b[i][j] = 1;
printf("%d %d %d\n",i,j,b[i][j]);
}
else if(c[i-1][j] >= c[i][j-1]) {
c[i][j] = c[i-1][j];
b[i][j] = 2;
printf("%d %d %d\n",i,j,b[i][j]);
}
else {
c[i][j] = c[i][j -1];
b[i][j] = 3;
printf("%d %d %d\n",i,j,b[i][j]);
}
}
}
}
void print(char x[],int i,int j,int b[100][100]){
if( i== 0 || j == 0) return;
if(b[i][j] == 1){
print(x,i-1,j-1,b);
printf("%c ",x[i]);
}
else if(b[i][j] == 2) {
print(x,i-1,j,b);
}
else print(x,i,j-1,b);
}
int main(){
scanf("%d",&m);
for(int i = 1;i<= m;i++){
getchar();
scanf("%c",&x[i]);
}
scanf("%d",&n);
for(int i = 1;i<= n;i++){
getchar();
scanf("%c",&y[i]);
}
LCSLength(x,y,c,b,m,n);
print(x,m,n,b);
system("pause");
return 0;
}
动态规划之最长公共子序列
最新推荐文章于 2024-10-01 18:52:56 发布