最长公共子序列 与 最长子序列 (C++实现)

// Type your C++ code and click the "Run Code" button!
// Your code output will be shown on the left.
// Click on the "Show input" button to enter input data to be read (from stdin).

#include <iostream>
using namespace std;

int check_in_list(int l[], int n, int e) {
    for(int i = 0; i < n; i++) {
        if(l[i] == e) return 1;
    }
    return 0;
}

// 最长公共子序列长度
int max_common_seq(int l1[], int m, int l2[], int n) {
    if (m==0 || n==0) return 0;
    if (m==1) return check_in_list(l2, n, l1[0]);
    if (n==1) return check_in_list(l1, m, l2[0]);
    
    int dp[100][100] = {0};
    
    // first line
    int temp = check_in_list(l1, m, l2[0]);
    if (temp) for(int i = 0; i < m; i++, dp[i][0] = temp);
    // first row
    temp = check_in_list(l2, n, l1[0]);
    if (temp) for(int j = 0; j < n; j++, dp[0][j] = temp);
    
    int ms = 0;
    
    for(int i = 1; i < m; i++) {
        for(int j = 1; j < n; j++) {
            if(l1[i] == l2[j]) dp[i][j] = dp[i-1][j-1]+1;
            else 
            dp[i][j] = max(
                dp[i][j-1],
                dp[i-1][j]
            );
            ms =  max(ms, dp[i][j]);
        }
    }
    return ms;
}
// 最长子序列长度
int max_seq(int l[], int n) {
    if (n <= 1) return n;
    int maxs = 0; 
    int lasts = 1;
    for (int i = 1; i < n; i++) {
        lasts = l[i] >= l[i-1] ? lasts+1 : 1;
        maxs = max(maxs, lasts);
    }
    return maxs;
}

int main() {
    // 测试最长子序列长度
    int l[] = {1, 3, 4, 2, 3, 1, 3, 2, 5, 6, 9, 11};
    cout<<max_seq(l, 11)<<endl;
    
    // 测试最长公共子序列长度
    int l1[] = {1, 4, 5, 7, 9, 10, 13};
    int l2[] = {1, 5, 7, 10, 8, 10, 13, 14};
    cout<<max_common_seq(l1, 7, l2, 8)<<endl;
    
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值