动态规划最长公共子序列问题

#include <iostream>
#include <cstring>
using namespace std;

template <typename T>
void LCS_Length(T* x, T* y, int m, int n, int** C, int** D) {
    for (int i = 0; i <= m; i++) {
        C[i][0] = 0;
    }

    for (int j = 0; j <= n; j++) {
        C[0][j] = 0;
    }

    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            if (i == 0 || j == 0) {
                C[i][j] = 0;
            } else if (x[i-1] == y[j-1]) {
                C[i][j] = C[i-1][j-1] + 1;
                D[i][j] = 1;
            } else {
                if (C[i-1][j] >= C[i][j-1]) {
                    C[i][j] = C[i-1][j];
                    D[i][j] = 2;
                } else {
                    C[i][j] = C[i][j-1];
                    D[i][j] = 3;
                }
            }
        }
    }
}

template <typename T>
void LCS_Print(int** D, T* x, int i, int j) {
    if (i == 0 || j == 0) {
        return;
    }
    if (D[i][j] == 1) {
        LCS_Print(D, x, i-1, j-1);
        cout << x[i-1];
    } else {
        if (D[i][j] == 2) {
            LCS_Print(D, x, i-1, j);
        } else {
            LCS_Print(D, x, i, j-1);
        }
    }
}

int main() {
    int x_len = 8;
    int y_len = 9;
    int x[] = {1, 0, 0, 1, 0, 1, 0, 1};
    int y[] = {0, 1, 0, 1, 1, 0, 1, 1, 0};

    //x_len = 11;
    //y_len = 10;
    //char x1[x_len];
    //char y1[y_len];
    //strncpy(x1, "AHPEULALGOW", x_len);
    //strncpy(y1, "HVEALQLPUO", y_len);

    int** C = new int*[x_len];
    int** D = new int*[x_len];
    for (int i =0; i <= x_len; i++) {
        C[i] = new int[y_len];
        D[i] = new int[y_len];
    }
    for (int i ; i <= x_len; i++) {
        for (int j; j <= y_len; j++) {
            C[i][j] = 0;
            D[i][j] = 0;
        }
    }

    LCS_Length(x, y, x_len, y_len, C, D);
    cout << "最大公共子序列: ";
    LCS_Print(D, x, x_len, y_len);
    cout <<endl;
    int l = C[x_len][y_len];
    cout << "最大公共子序列长度: " << l << endl;
    for (int i =0; i <= x_len; i++) {
        delete[] C[1];
        delete[] D[i];
    }
    delete[] C;
    delete[] D;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值