题目描述
题解
首先考虑如果k=1的时候如何来做。当k=1时,也就是只选出来一个最大值就可以了,我们可以枚举区间的起点,每一个起点对应的一个区间长度合法的区间,从这段区间里找出来一个前缀和最大的然后减去起点的就可以了。
但是如果k>1的话,我们不能只找一个最大的。那么可以考虑维护一个大根堆,每次弹出堆中最大的元素来,弹k次。还是像k=1时那样,每次找出来一个最大值,然后压到堆里。每次从堆中弹出一个最大的,这个最大的还记录的一些信息:起点head,合法区间的lr,以及取最大值的位置loc,那么找出这个最大值之后计入答案,然后再将同样是head为起点,[l,loc-1]和[loc+1,r]的最大值压入堆。这样就贪心地找出了前k大的。时间复杂度
O(klogn)
。
代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<cmath>
using namespace std;
#define N 500005
#define sz 19
#define LL long long
int n,k,l,r;
int a[N],s[N];
struct hp
{
int val,loc,l,r,head;
bool operator < (const hp &a) const
{
return a.val>val;
}
};
hp st[N][sz+5];
priority_queue <hp> q;
LL ans;
void init()
{
for (int i=1;i<=n;++i) st[i][0].val=s[i],st[i][0].loc=i;
for (int j=1;j<sz;++j)
for (int i=1;i<=n;++i)
if (i+(1<<j)-1<=n)
{
if (st[i][j-1].val>=st[i+(1<<(j-1))][j-1].val)
st[i][j]=st[i][j-1];
else
st[i][j]=st[i+(1<<(j-1))][j-1];
}
}
hp query(int L,int R)
{
int k=log2(R-L+1);
if (st[L][k].val>=st[R-(1<<k)+1][k].val)
return st[L][k];
else return st[R-(1<<k)+1][k];
}
void add(int L,int R,int head)
{
if (L>R) return;
hp now=query(L,R);
now.val-=s[head-1],now.l=L,now.r=R,now.head=head;
q.push(now);
}
int main()
{
scanf("%d%d%d%d",&n,&k,&l,&r);
for (int i=1;i<=n;++i) scanf("%d",&a[i]),s[i]=s[i-1]+a[i];
init();
for (int i=1;i<=n;++i)
{
if (i+l-1>n) continue;
int L=min(n,i+l-1),R=min(n,i+r-1);
add(L,R,i);
}
while (k--)
{
hp now=q.top();q.pop();
ans+=(LL)now.val;
add(now.l,now.loc-1,now.head);
add(now.loc+1,now.r,now.head);
}
printf("%lld\n",ans);
}