void print_LCS(char** matrix, char* a, char* b, int i, int j) { if (i == 0 || j == 0) return; if (a[i - 1] == b[j - 1]) { print_LCS(matrix, a, b, i - 1, j - 1); printf("%c", a[i - 1]); } else if (matrix[i][j] == matrix[i - 1][j]) print_LCS(matrix, a, b, i - 1, j); else print_LCS(matrix, a, b, i, j - 1); }
void print_LCS(int i, int j) { // 第一個或第二個序列為空集合就停止 if (i==0 || j==0) return; if (direction[i][j] == 1) { print_LCS(i-1, j-1); printf("%c ", input1[i-1]); // 印出LCS的元素 } else if (direction[i][j] == 3) print_LCS(i-1, j); else if (direction[i][j] == 2) print_LCS(i, j-1); }
int main(int argc, char** argv) { if (argc < 3) { puts("Nombre de parametres insuffisants"); return 1; } size_a = strlen(argv[1]); size_b = strlen(argv[2]); // int size_lcs = get_size_of_lcs(argv[1], argv[2], 0, 0); // printf("%d\n", size_lcs); char** matrix = build_path(argv[1], argv[2]); display_matrix(matrix, size_a+2, size_b+2); print_LCS(matrix, argv[1], argv[2], size_a, size_b); return 0; }
int main(){ printf("input the first string : "); scanf("%s",input1); printf("input the second string : "); scanf("%s",input2); int input1_length = strlen(input1); int input2_length = strlen(input2); for(int i=0;i<input1_length;i++){ for(int j=0;j<input2_length;j++){ if(input1[i] == input2[j]){ lcs[i+1][j+1] = lcs[i][j] + 1; direction[i+1][j+1] = 1; }else{ if (lcs[i][j+1] < lcs[i+1][j]) { lcs[i+1][j+1] = lcs[i+1][j]; direction[i+1][j+1] = 2; } else { lcs[i+1][j+1] = lcs[i][j+1]; direction[i+1][j+1] = 3; } } } } for(int i=0;i<=input1_length;i++){ for(int j=0;j<=input2_length;j++){ printf("%d ",lcs[i][j]); } printf("\n"); } printf("LCS的長度是%d\n", lcs[input1_length][input2_length]) ; printf("LCS是\n"); print_LCS(input1_length, input2_length); system("pause"); return 0; }