Codeforces10D LCIS

原题链接:Codeforces10D

题目大意:如题

LICS

因为需要输出方案,des记录最后一个位置,pre[]存前驱,des必须初始化为$0$,否则当LICS长度为$0$的时候,des不会被更新,dfs(des)就会RE

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

const int N = 510;

int n, m;
int a[N], b[N];
int f[N][N];
int pre[N];

void dfs(int u) {   
    if (!u) return;
    dfs(pre[u]);
    cout << b[u] << " ";
}

int main() {
    cin >> n;
    for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
    cin >> m;
    for (int i = 1; i <= m; i++) scanf("%d", &b[i]);
    for (int i = 1; i <= n; i++) {   
        int maxv = 0, last = 0; 
        for (int j = 1; j <= m; j++) {   
            f[i][j] = f[i - 1][j];
            if (a[i] == b[j]) {   
                if (f[i][j] < maxv + 1) {
                    f[i][j] =  maxv + 1;
                    pre[j] = last;
                }   
            }
            if (b[j] < a[i]) {   
                if (f[i][j] > maxv) {
                    maxv  = f[i][j];
                    last = j;
                }
            }
        }
    }
    int res = 0, des = 0;
    for (int i = 1; i <= m; i++) {
        if (f[n][i] > res) {
            res = max(res, f[n][i]);
            des = i;
        }
    }
    cout << res << endl;
    dfs(des);
    return 0;
}
updatedupdated2020-05-192020-05-19
加载评论
点击刷新