跳到正文

题解

P2048 [NOI2010]超级钢琴(贪心 + 堆 + ST表维护RMQ)

木xx木大约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年1月18日
更新
2026年1月18日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1

P2048 [NOI2010]超级钢琴

  • 首先对整个序列求前缀和。

  • 定义 MAX(o,l,r)=max⁡{sum(t)−sum(o−1)∣l≤t≤r}MAX(o,l,r)=\max \{sum(t)−sum(o−1)∣l≤t≤r\} ,即以 oo 为左端点,右端点范围是 [l,r][l, r] 的最大子段。sumsum 即前缀和。对于每个固定的 oo,sum(o−1)sum(o−1) 是固定的。所以我们要求最大值,只要求 sum(t)sum(t) 在 [l,r][l, r] 中的最大值。用 ST 表维护 [l,r][l, r] 中 sum(t)sum(t) 最大时 tt 的位置。

  • 贪心地选出前 kk 个最优的子段,其和即为 ansans 。用堆维护当前最优解。

  • 设一个三元组 (o,l,r)(o, l, r) 表示以 oo 为左端点,右端点的选择区间为 [l,r][l, r] 的情况,对每一个三元组顺便记录一下最优解位置 tt 。

  • 假设当前最优三元组是(o,l,r)(o, l, r)。 ansans 累加这个三元组的贡献。对于这个 oo,tt 不能再次选中,但最优解还可能存在于 tt 左右的两端区间中,所以删去 (o,l,r)(o, l, r) 之后,还要把 (o,l,t−1)(o, l, t - 1),(o,t+1,r)(o, t + 1, r) 扔回堆里。注意:在放回去之前应该保证区间的存在,即 l≠t,r≠tl\neq t,r\neq t。

C++
#include<bits/stdc++.h>
using namespace std;
int sum[500005],n,k,L,R;
int pos[500005][25];
long long ans;
void init()
{
	for(int i=1;i<=n;i++)
		pos[i][0]=i;
	for(int j=1;j<=21;j++)
		for(int i=1;i+(1<<j)-1<=n;i++)
		{
			int x=pos[i][j-1],y=pos[i+(1<<(j-1))][j-1];
			pos[i][j]=sum[x]>sum[y]? x:y;
		}
}
int query(int l,int r)
{
	int k=log2(r-l+1);
	int x=pos[l][k],y=pos[r-(1<<k)+1][k];
	return sum[x]>sum[y]? x:y;
}
struct Node{
	int o,l,r,t;
	Node(int _o,int _l,int _r)
	{
		o=_o;
		l=_l;
		r=_r;
		t=query(l,r);
	}
};
bool operator <(Node x,Node y)
{
	return sum[x.t]-sum[x.o-1]<sum[y.t]-sum[y.o-1];
}
priority_queue<Node> q;
int main()
{
	scanf("%d%d%d%d",&n,&k,&L,&R);
	for(int i=1;i<=n;i++)
	{
		int a;
		scanf("%d",&a);
		sum[i]=sum[i-1]+a;
	}
	init();
	for(int i=1;i<=n-L+1;i++)
		q.push(Node(i,i+L-1,min(i+R-1,n)));
	while(k--)
	{
		Node x=q.top();
		q.pop();
		ans+=sum[x.t]-sum[x.o-1];
		if(x.l!=x.t)q.push(Node(x.o,x.l,x.t-1));
		if(x.r!=x.t)q.push(Node(x.o,x.t+1,x.r));
	}
	printf("%lld",ans);
	return 0;
}
原文