大意: 给定n元素序列a, 定义一个区间的权值为区间内所有元素和, 求前k大的长度在[L,R]范围内的区间的权值和.
固定右端点, 转为查询左端点最小的前缀和, 可以用RMQ O(1)查询.
要求的是前$k$大, 可以用堆维护可供选择的区间, 每次取出最大的即可
#include <iostream> #include <algorithm> #include <cstdio> #include <math.h> #include <set> #include <map> #include <queue> #include <string> #include <string.h> #include <bitset> #define REP(i,a,n) for(int i=a;i<=n;++i) #define PER(i,a,n) for(int i=n;i>=a;--i) #define hr putchar(10) #define pb push_back #define lc (o<<1) #define rc (lc|1) #define mid ((l+r)>>1) #define ls lc,l,mid #define rs rc,mid+1,r #define x first #define y second #define io std::ios::sync_with_stdio(false) #define endl ' ' using namespace std; typedef long long ll; typedef pair<int,int> pii; const int P = 1e9+7, INF = 0x3f3f3f3f; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;} ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;} //head const int N = 1e6+10; int n, k, L, R; int Log[N], a[N], f[N][20]; int RMQ(int l, int r) { int k=Log[r-l+1]; int x=f[l][k],y=f[r-(1<<k)+1][k]; return a[x]<a[y]?x:y; } struct _ { int l,r,opt,pos,v; _ () {} _ (int l,int r,int pos) : l(l),r(r),pos(pos) { opt = RMQ(l,r); v = a[pos]-a[opt]; } bool operator < (const _ & rhs) const { return v < rhs.v; } }; priority_queue<_> q; int main() { scanf("%d%d%d%d", &n, &k, &L, &R); REP(i,1,n) scanf("%d",a+i),a[i]+=a[i-1]; Log[0]=-1; REP(i,1,n) f[i][0]=i,Log[i]=Log[i>>1]+1; for (int j=1; (1<<j)<=n; ++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]=a[x]<a[y]?x:y; } } REP(i,L,n) q.push(_(max(0,i-R),i-L,i)); ll ans = 0; REP(i,1,k) { _ t = q.top();q.pop(); ans += t.v; if (t.opt!=t.l) q.push(_(t.l,t.opt-1,t.pos)); if (t.opt!=t.r) q.push(_(t.opt+1,t.r,t.pos)); } printf("%lld ", ans); }