CodeForces-1077F2 Pictures with Kittens (hard version)题解

· · 个人记录

CodeForces-1077F2 Pictures with Kittens (hard version)题解

思路讲解

状态: dp _ {c, i} 表示选取了 c 张图片,且最后一张图片位置为 i 时的最大美丽度之和。

转移: \begin{aligned} dp _ {c, i} = \max _ {j = max(1, i - k)} ^ {i - 1} (dp[j]) + a _ {i} \end{aligned}

上述空间复杂度为 O(XN) ,时间复杂度为 O(X · N ^ 2) 。

这时我们发现“ \begin{aligned} \max _ {j = max(1, i - k)} ^ {i - 1} \end{aligned} ”这一部分可以用单调队列来维护。

这时的空间复杂度为 O(XN) ,时间复杂度为 O(XN) 。

代码

#include <bits/stdc++.h>

using namespace std;
using ll = long long;

const int N = 5e3 + 5;
const ll INF = 1e18;

int n, k, x, a[N], que[N];
ll dp[N][N];

int main() {
    ios::sync_with_stdio(0), cin.tie(0);
    cin >> n >> k >> x;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    for (int i = 0; i <= x; i++) {
        for (int j = 0; j <= n; j++) {
            dp[i][j] = -INF;
        }
    }
    for (int i = 1; i <= k; i++) {
        dp[1][i] = a[i];
    }
    for (int i = 2; i <= x; i++) {
        int h = 1, t = 0;
        for (int j = 1; j <= n; j++) {
            while (h <= t && que[h] < j - k) {
                h++;
            }
            while (h <= t && dp[i - 1][que[t]] <= dp[i - 1][j - 1]) {
                t--;
            }
            que[++t] = j - 1;
            if (h <= t) {
                dp[i][j] = dp[i - 1][que[h]] + a[j];
            }
        }
    }
    ll ans = -INF;
    for (int i = n - k + 1; i <= n; i++) {
        ans = max(ans, dp[x][i]);
    }
    cout << (ans < 0 ? -1 : ans);
    return 0;
}