BZOJ2006超级钢琴
考虑对于每一个i作为右端点,使得它这段和最大的j是[i-R,i-L]区间内sum[j-1]最小的
所以我们开一个堆来维护一个四元组信息(i,l,r,t)
表示右端点为i,左端点取值范围在[l,r]中,当前这段区间中sum最小值为t
显然t取了,这个四元组就被分裂成两个了,为(i,l,t-1,rmq)和(i,t+1,r,rmq)
做K次就行了
代码如下:
#include<bits/stdc++.h> #define N 500005 #define int long long using namespace std; int sum[N],a[N],lg[N],f[N][20],n,K,l,r,ans; inline int min(int x,int y){if(sum[x]<=sum[y])return x;return y;} struct node{int l,r,id,minpos;}; bool operator < (node aa,node bb){return sum[aa.id]-sum[aa.minpos]<sum[bb.id]-sum[bb.minpos];} priority_queue<node>Q; inline void init(){ for (int i=0;i<=n;i++) f[i][0]=i; for (int j=1;j<=19;j++){ for (int i=0;i+(1<<j)-1<=n;i++) { int x=f[i][j-1],y=f[i+(1<<(j-1))][j-1]; f[i][j]=min(x,y); } } } inline int query(int L,int R){ int k=lg[R-L+1]; return min(f[L][k],f[R-(1<<k)+1][k]); } signed main(){ scanf("%lld%lld%lld%lld",&n,&K,&l,&r); lg[0]=-1;for (int i=1;i<=n;i++) lg[i]=lg[i>>1]+1; for (int i=1;i<=n;i++) scanf("%lld",&a[i]); for (int i=1;i<=n;i++) sum[i]=sum[i-1]+a[i]; init(); for (int i=1;i<=n;i++) if (i-l>=0) Q.push((node){max(1ll*0,i-r),max(1ll*0,i-l),i,query(max(1ll*0,i-r),max(1ll*0,i-l))}); while (K--){ node tmp=Q.top(); int x=tmp.minpos;int y=tmp.id; Q.pop(); ans=ans+sum[y]-sum[x]; if (tmp.minpos-1>=tmp.l) Q.push((node){tmp.l,x-1,tmp.id,query(tmp.l,x-1)}); if (tmp.r>=tmp.minpos+1) Q.push((node){x+1,tmp.r,tmp.id,query(x+1,tmp.r)}); } printf("%lld\n",ans); return 0; }