[Noi2010] D1T2 超级钢琴 (ST表 线段树 主席树)

大概就是对于每个i求一下可行区间里的最大值。
但是有可能次大值也在答案中。
所以每次选取最大值时顺便将次大值也加入堆中。
复杂度O(n log n)

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <map>
#include <queue>
#define INF 0x3f3f3f3f
using namespace std;

const int N = 500005;

inline void read( int &res )
{
    char ch = getchar(); res = 0; int flag = 1;
    while(ch < '0' || ch > '9') {if(ch == '-') flag = -1; ch = getchar();}
    while(ch >= '0' && ch <= '9') res = res * 10 + ch - 48, ch = getchar();
    res *= flag;
}

int n, k, L, R, a[N], sum[N], rmq[N][21], llg[N];

void Pre()
{
    for(int i = 1; i <= n; ++i) rmq[i][0] = i;
    for(int k = 1; k <= 19; ++k)
        for(int i = 1; i + (1 << k) - 1 <= n; ++i)
            if(sum[rmq[i][k - 1]] > sum[rmq[i + (1 << (k - 1))][k - 1]])
                rmq[i][k] = rmq[i][k - 1];
            else rmq[i][k] = rmq[i + (1 << (k - 1))][k - 1];
}

int Query( int L, int R )
{
    int k = llg[R - L + 1];
    if(sum[rmq[L][k]] > sum[rmq[R - (1 << k) + 1][k]])
        return rmq[L][k];
    else return rmq[R - (1 << k) + 1][k];
}

struct Node
{
    int lf, rg, pos, tmp;
    Node() {    }
    Node( int lf, int rg, int pos, int tmp ) : lf(lf), rg(rg), pos(pos), tmp(tmp) { }
    bool operator < ( const Node &g ) const
    {
        return sum[pos] - sum[tmp - 1] < sum[g.pos] - sum[g.tmp - 1];
    }
};

priority_queue< Node > que;

int main()
{

    read(n), read(k), read(L), read(R);
    for(int i = 2; i <= n; ++i) llg[i] = llg[i >> 1] + 1;
    for(int i = 1; i <= n; ++i) 
        read(a[i]), sum[i] = sum[i - 1] + a[i];
    Pre();
    for(int i = 1; i + L - 1 <= n; ++i)
    {
        int ps = min(i + R - 1, n);
        int as = Query(i + L - 1, ps);
        que.push(Node(i + L - 1, ps, as, i));
    }
    long long ans = 0;
    for(int i = 1; i <= k; ++i)
    {
        Node chs;
        chs = que.top();
        ans += (long long)sum[chs.pos] - sum[chs.tmp - 1];
        que.pop();
        int lf = chs.lf, rg = chs.rg;
        if(chs.pos > lf) que.push(Node(lf, chs.pos - 1, Query(lf, chs.pos - 1), chs.tmp));
        if(chs.pos < rg) que.push(Node(chs.pos + 1, rg, Query(chs.pos + 1, rg), chs.tmp));
    }
    cout << ans << endl;
    return 0;
}
/*
4 3 2 3
3
2
-6
8
*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值