[题解]P2048 [NOI2010] 超级钢琴(st表+贪心+堆)
Glassy_Sky · · 个人记录
题目
题意:
有
要求选取区间的长度在
-
区间可以重叠,但不能完全相同
-
n \le 500000 , k \le 500000 ,-1000 \le a_i \le 1000 , 1 \le L \le R \le n. -
保证有解
分析:
枚举每个左端点,考虑可以选取的右端点的区间为:
做一次前缀和,最大区间和 即为查找
用 st表 维护即可。
再用堆来查找当前的最大值。
考虑用三元组
因为一个区间不能使用多次,所以用过的
设使用过的右端点为
重复取
code:
#include<bits/stdc++.h>
using namespace std;
const int maxn=5e5+5;
int n,k,a[maxn],l,r;
int s[maxn],maxx[maxn][19],p[maxn][19];
struct node {
int now,L,R;
int pos,data;
bool operator < (node t) const {
return data<t.data;
}
};
priority_queue<node>q;
int f(int now,int L,int R,int& pos) {
int t=__lg(R-L+1);
int t1=maxx[L][t],t2=maxx[R-(1<<t)+1][t];
int ret;
if(t1>t2) ret=t1,pos=p[L][t];
else ret=t2,pos=p[R-(1<<t)+1][t];
ret-=s[now-1];
return ret;
}
int main() {
scanf("%d%d%d%d",&n,&k,&l,&r);
for(int i=1;i<=n;i++) {
scanf("%d",&a[i]);
s[i]=a[i]+s[i-1];
maxx[i][0]=s[i];
p[i][0]=i;
}
for(int i=1;i<=18;i++)
for(int j=1;j+(1<<i-1)<=n;j++) {
int t1=maxx[j][i-1],t2=maxx[j+(1<<i-1)][i-1];
if(t1>t2) maxx[j][i]=t1,p[j][i]=p[j][i-1];
else maxx[j][i]=t2,p[j][i]=p[j+(1<<i-1)][i-1];
}
for(int i=1;i<=n;i++) {
int L=i+l-1,R=min(i+r-1,n);
if(n<L) continue;
int pos,data=f(i,L,R,pos);
q.push((node){i,L,R,pos,data});
}
long long ans=0;
while(k--) {
node t=q.top();
q.pop();
ans+=t.data;
if(t.L<=t.pos-1) {
int pos,data=f(t.now,t.L,t.pos-1,pos);
q.push((node){t.now,t.L,t.pos-1,pos,data});
}
if(t.pos+1<=t.R) {
int pos,data=f(t.now,t.pos+1,t.R,pos);
q.push((node){t.now,t.pos+1,t.R,pos,data});
}
}
printf("%lld",ans);
return 0;
}