P2048 [NOI2010] 超级钢琴
xixihaha2021 · · 个人记录
P2048 [NOI2010] 超级钢琴
题意简述
在给定序列
思路简述
显然我们希望找到区间和前
当确定了一个左界后,找到使得区间之和最大的右界是容易的。具体地,对序列 RMQ 问题,使用 ST 表求解即可。
我们称如上的已知左界和右界范围求右界的问题为一个子问题。那么我们针对每种可能的左界设立一个子问题,满足序列长度属于
然而,当我们取出某个子问题后,设答案区间为
时间复杂度
代码实现
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,k,l,r,st[500005][24],pre[500005],lg[500005],ans,temp;
struct Node{
ll p,l,r;
bool operator<(const Node &x)const{
return max(pre[st[l][lg[r - l + 1]]],pre[st[r - (1 << lg[r - l + 1]) + 1][lg[r - l + 1]]]) - pre[p - 1] < max(pre[st[x.l][lg[x.r - x.l + 1]]],pre[st[x.r - (1 << lg[x.r - x.l + 1]) + 1][lg[x.r - x.l + 1]]]) - pre[x.p - 1];
}
}tmp;
priority_queue<Node> q;
ll read(){
ll x = 0;
bool f = true;
char ch = getchar();
while(!isdigit(ch)){
if(ch == '-')f = !f;
ch = getchar();
}
while(isdigit(ch))x = x * 10 + ch - '0',ch = getchar();
return x * f * 2 - x;
}
ll write(ll x,string ch){
ll f = 1,L = ch.size(),tmp = x;
if(tmp < 0){
putchar('-');
tmp *= -1;
}
while(f <= tmp)f *= 10;
if(tmp)f /= 10;
while(f){
putchar(tmp / f + '0');
tmp -= (tmp / f * f),f /= 10;
}
for(ll i = 0;i <= L - 1;i++)putchar(ch[i]);
return x;
}
int main(){
n = read(),k = read(),l = read(),r = read();
for(ll i = 1;i <= n;i++)st[i][0] = i,pre[i] = pre[i - 1] + read();
for(ll i = 1,k = 0;i <= n;i *= 2,k++)for(ll j = i;j <= min(i * 2 - 1,n);j++)lg[j] = k;
for(ll j = 1;j <= lg[n];j++)for(ll i = 1;i + (1 << j) - 1 <= n;i++)st[i][j] = pre[st[i][j - 1]] > pre[st[i + (1 << (j - 1))][j - 1]] ? st[i][j - 1] : st[i + (1 << (j - 1))][j - 1];
for(ll i = 1;i <= n;i++)if(i + l - 1 <= n)q.push((Node){i,i + l - 1,min(i + r - 1,n)});
for(ll i = 1;i <= k;i++){
Node tmp = q.top();
q.pop();
temp = pre[st[tmp.l][lg[tmp.r - tmp.l + 1]]] > pre[st[tmp.r - (1 << lg[tmp.r - tmp.l + 1]) + 1][lg[tmp.r - tmp.l + 1]]] ? st[tmp.l][lg[tmp.r - tmp.l + 1]] : st[tmp.r - (1 << lg[tmp.r - tmp.l + 1]) + 1][lg[tmp.r - tmp.l + 1]];
ans += pre[temp] - pre[tmp.p - 1];
if(tmp.l != temp)q.push((Node){tmp.p,tmp.l,min(temp - 1,n)});
if(tmp.r != temp)q.push((Node){tmp.p,temp + 1,tmp.r});
}
write(ans,"");
return 0;
}