最长公共子序列 与 最长子序列 (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;
}

 

你可能感兴趣的:(C++)