bzoj2442(单调队列优化)

我们很容易想到nk的做法:
定义f[i]为前i个数这样分的方法
那么转移为f[i]=max(f[j2]+sum[j][i]) (ik+1<=j<=i)
改成前缀和f[i]=max(f[j2]+sum[i]sum[j1]) (ik+1<=j<=i)
若一个点比另一个优,(设k比j优),那么f[k - 2] + sum[i] - sum[k - 1] > f[j - 2] + sum[i] - sum[j - 1], 即f[k - 2] - sum[k - 1] > f[j - 2] - sum[j - 1]。我们用单调队列维护就好
一开始把while写成if调了半天,QAQ

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cmath>

const int N = 1e5 + 10;
int n, k, head = 1, tail = 1;
long long sum[N], f[N];
struct item {
    int id;
    long long data;
    item () {}
    item (int id, long long data) : id (id), data (data) {}
    bool operator >= (const item &rhs) const {
        return data >= rhs.data;
    }
}q[N], hel;

int main () {
    scanf ("%d%d", &n, &k);
    q[1] = item (1, 0);
    for (int i = 1; i <= n; ++i) {
        scanf ("%lld", sum + i); sum[i] += sum[i - 1];
        if (i >= 2) {
            hel = item (i, f[i - 2] - sum[i - 1]);
            while (head <= tail && hel >= q[tail]) --tail;
            q[++tail] = hel;
        }
        while (head <= tail && i - k + 1 > q[head].id) ++head;
        f[i] = std :: max (q[head].data + sum[i], f[i - 1]);
    }
    printf ("%lld\n", f[n]);
    return 0;
}
posted @ 2016-08-23 11:40  DraZxlnDdt  阅读(173)  评论(0编辑  收藏  举报