272. 最长公共上升子序列(动态规划)

 方法一:O(n3)

#include <bits/stdc++.h>
using namespace std;

const int N = 3030;
int a[N], b[N], f[N][N];
int n;

int main() {
    scanf("%d",&n);
    for(int i = 1; i <= n; i++) scanf("%d",&a[i]);
    for(int i = 1; i <= n; i++) scanf("%d",&b[i]);
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= n; j++) {
            f[i][j] = f[i-1][j];
            if(a[i] == b[j]) {
                int max1 = 1;
                for(int k = 1; k < j; k++) {
                    if(a[i] > b[k]) max1 = max(max1,f[i-1][k] + 1);
                }
                f[i][j] = max1;
            }
        }
    }
    int res = 0;
    for(int i = 1; i <= n; i++) res = max(res,f[n][i]);
    cout << res << endl;
    return 0;
} 

方法二O(n2)

#include <bits/stdc++.h>
using namespace std;

const int N = 3030;
int a[N], b[N], f[N][N];
int n;

int main() {
    scanf("%d",&n);
    for(int i = 1; i <= n; i++) scanf("%d",&a[i]);
    for(int i = 1; i <= n; i++) scanf("%d",&b[i]);
    for(int i = 1; i <= n; i++) {
        int maxv = 1;
        for(int j = 1; j <= n; j++) {
            f[i][j] = f[i-1][j];
            if(a[i] == b[j]) f[i][j] = max(f[i][j],maxv);
            if(a[i] > b[j]) maxv = max(maxv,f[i][j] + 1);
        }
    }
    int res = 0;
    for(int i = 1; i <= n; i++) res = max(res,f[n][i]);
    cout << res << endl;
    return 0;
} 

 

posted @ 2020-09-21 10:25  Sexyomaru  阅读(552)  评论(0编辑  收藏  举报