Acwing272 最长公共上升子序列

题目大意:给定两个大小为n的数组,让你找出最长公共上升子序列的长度。

分析:这是一个比较好的dp题,LIS和LCS两大经典线性dp问题相结合,简称LCIS。

代码(O(n*n*n)写法):

#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e3+7;
int a[maxn],b[maxn];
int dp[maxn][maxn];
int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    for (int i = 1; i <= n; i++)
        cin >> b[i];
    a[0] = b[0] = -0x3f3f3f3f;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            if (a[i] == b[j]) {
                for (int k = 0; k < j; k++) {
                    if (b[k] < a[i])
                        dp[i][j] = max(dp[i][j], dp[i - 1][k] + 1);
                }
            } else dp[i][j] = dp[i - 1][j];
        }
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            ans = max(ans, dp[i][j]);
        }
    }
    cout << ans << endl;
    return 0;
}

代码(O(n*n)写法):

#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e3+7;
int a[maxn],b[maxn];
int dp[maxn][maxn];
int main() {
    int n;
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    for (int i = 1; i <= n; i++)
        cin >> b[i];
    a[0] = b[0] = -0x3f3f3f3f;
    for (int i = 1; i <= n; i++) {
        int val = 0;
        if (b[0] < a[i]) val = dp[i - 1][0];
        for (int j = 1; j <= n; j++) {
            if (a[i] == b[j])
                dp[i][j] = val + 1;
            else
                dp[i][j] = dp[i - 1][j];
            if (b[j] < a[i])
                val = max(val, dp[i - 1][j]);
        }
    }
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++)
            ans = max(ans, dp[i][j]);
    }
    cout << ans << endl;
    return 0;
}
posted @ 2020-01-15 20:07  SwiftAC  阅读(104)  评论(0编辑  收藏  举报