bzoj2006 [NOI2010] Super Piano (st table + heap)

Find the top K of the sum of consecutive subsegments.
Make a prefix sum and turn the subsegment sum into sum[r]-sum[l].
When considering r=i, the left endpoint must be the smallest one within a range.
It can be obtained in O(1) with st table + rmq.
We can throw these into the priority queue and greedily take the largest one.
Consider that for i, after I have selected x in the optional interval [l, r], the other may be larger than the first k. But it is difficult for us to delete x. So we split [l,r] into two halves [l,x-1],[x+1,r]. That's it.
So our priority queue needs to maintain the difference, the selected interval and i.
the complexity O ( n l o gn+Klog(n+2k))

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 500010
inline char gc(){
    static char buf[1<<16],*S,*T;
    if(S==T){T=(S=buf)+fread(buf,1,1<<16,stdin);if(T==S) return EOF;}
    return *S++;
}
inline int read(){
    int x=0,f=1;char ch=gc();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=gc();
    return x*f;
}
int n,K,L,R,sum[N],mn[N][20],Log[N];ll ans=0;
struct data{
    int l,r,val,x;
    data(int _val,int _l,int _r,int _x){val=_val;l=_l;r=_r;x=_x;}
};
struct cmp{
    bool operator()(data a,data b){return a.val<b.val;}
};
priority_queue<data,vector<data>,cmp>q;
inline int Min(int x,int y){return sum[x]<sum[y]?x:y;}
inline int rmq(int l,int r){
    int t=Log[r-l+1];
    return Min(mn[l][t],mn[r-(1<<t)+1][t]);
}
int main(){
//  freopen("a.in","r",stdin);
    n=read();K=read();L=read();R=read();Log[0]=-1;
    for(int i=1;i<=n;++i) sum[i]=sum[i-1]+read();
    for(int i=1;i<=n+1;++i) Log[i]=Log[i>>1]+1,mn[i][0]=i;
    for(int i=1;i<=Log[n+1];++i)
        for(int j=0;j<=n;++j){
            if(j+(1<<i-1)>n) break;
            mn[j][i]=Min(mn[j][i-1],mn[j+(1<<i-1)][i-1]);
        }
    for(int i=L;i<=n;++i)
        q.push(data(sum[i]-sum[rmq(max(i-R,0),i-L)],max(i-R,0),i-L,i));
    while(K--){
        int x=q.top().x,l=q.top().l,r=q.top().r,y=rmq(l,r);
        ans+=q.top().val;q.pop();
        if(l<=y-1) q.push(data(sum[x]-sum[rmq(l,y-1)],l,y-1,x));
        if(y+1<=r) q.push(data(sum[x]-sum[rmq(y+1,r)],y+1,r,x));
    }printf("%lld\n",ans);
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325737900&siteId=291194637