#include <stdio.h>
#include <string.h> 
#define MAX 100  
int getLCS(char* text1, char* text2) {
    int t1_len = strlen(text1);
    int t2_len = strlen(text2);
    int dp[MAX][MAX] = {0}; 
    for (int i = 1; i <= t1_len; i++) {
        for (int j = 1; j <= t2_len; j++) {
            if (text1[i - 1] == text2[j - 1]) {
                //找到一个 lcs 的元素，继续往前找
                dp[i][j] = 1 + dp[i - 1][j - 1];
            } else {//谁能让 lcs 最长，就取谁的值
                dp[i][j] = (dp[i - 1][j] > dp[i][j - 1])?
                           dp[i - 1][j] : dp[i][j - 1];
            }
        }
    }
    return dp[t1_len][t2_len];
}

void getLCSTable(int dp[MAX][MAX], char* text1, char* text2, char b[MAX][MAX]) {
    int t1_len = strlen(text1);
    int t2_len = strlen(text2);    
    for (int i = 1; i <= t1_len; i++) {
        for (int j = 1; j <= t2_len; j++) {
            if (text1[i - 1] == text2[j - 1]) {
                dp[i][j] = 1 + dp[i - 1][j - 1];
                b[i][j] = 'X'; // LCS元素，使用 'X' 作为占位符
            } else if (dp[i - 1][j] >= dp[i][j - 1]) {
                dp[i][j] = dp[i - 1][j];
                b[i][j] = '|'; // 取上面的值
            } else {
                dp[i][j] = dp[i][j - 1];
                b[i][j] = '-'; // 取左边的值
            }
        }
    }
}

void printLCSTable(char b[MAX][MAX], char* t1, char* t2, int l1, int l2) {
    printf("\t");
    for (int j = 0; j < l2; j++)  
        printf("%c\t", t2[j]); 
    printf("\n"); 
    for (int i = 0; i <= l1; i++) {
        printf("%c\t", (i == 0) ? ' ' : t1[i - 1]);
        for (int j = 0; j <= l2; j++) {
            if (i == 0 && j == 0) {
                printf("\t");
            } else {
                printf("%c\t", b[i][j]);
            }
        }
        printf("\n");
    }
}

void printLCSString(char b[MAX][MAX], char* x, int i, int j) {
    if (i == 0 || j == 0) return; 
    if (b[i][j] == 'X') {
        printLCSString(b, x, i - 1, j - 1);
        // 打印当前字符
        printf("%c", x[i - 1]);
    } else if (b[i][j] == '|') {
        printLCSString(b, x, i - 1, j);
    } else {
        printLCSString(b, x, i, j - 1);
    }
}

int main() {
    char t1[] = "ABCB";
    char t2[] = "BDCA"; 
    printf("字符串: %s 和字符串: %s 的 LCS 长度为: %d\n", t1, t2, getLCS(t1, t2));
    printf("--------------------------------\n"); 
    int dp[MAX][MAX] = {0};
    char b[MAX][MAX] = {0};
    getLCSTable(dp, t1, t2, b);
    printLCSTable(b, t1, t2, strlen(t1), strlen(t2));
    printf("-------------------------------\n");
    
    printf("LCS 字符串为: ");
    printLCSString(b, t1, strlen(t1), strlen(t2));
    printf("\n");

    return 0;
}
