跳到正文

题解

题解:P17246 【Gensokyo OI Round 2】长夜梦难却

ProjectMili约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年8月12日
收录
2026年8月13日
更新
2026年11月15日
篇幅
约 5 分钟
题目
P17246

版本

  1. v1当前

本蒟蒻刚学线段树不久来打比赛结果赛时被硬控2h只骗到了20分。

题目要求最大收益,考虑贪心。


对于每次操作,xx 显然越大越好。于是我们从大到小枚举 xx,这样可以保证每一次操作都是局部最优解;同时我们也希望对当前的 xx 执行尽可能多次的操作,而可执行的最大操作次数取决于 x−k∼x+kx-k \sim x+k 范围内元素个数的最小值。

附上扯淡简略贪心正确性证明:

每次操作消耗序列中值为 x−k∼x+kx-k \sim x+k 的元素各一个,注意到区间 [x−k,x+k][x-k,x+k] 长度固定。对于任意合法的 x1<x2x_1<x_2,我们总能以值为 x2x_2 的操作消耗掉与值为 x1x_1 的操作相同的元素数量,而收益不减,从而得到全局最优解。

那么问题来了:我们需要一种能够快速执行区间修改和最值查询的数据结构。

没错,就是线段树。(用来做这道题的是支持区间减和最小值查询的线段树,维护的是序列 aa 的桶数组)

AC代码
C++
#include<iostream>
#include<climits>
#include<algorithm>
//个人不太习惯用万能头
using namespace std;

const int N=1e6+5;
int n,k,f[N],maxn=-2e9;

struct segment{
	int val,lzy;
}tree[N<<2];
//线段树,val存储最小值,lzy是懒标记

#define lson root<<1
#define rson root<<1|1

void pushup(int root){
	tree[root].val=min(tree[lson].val,tree[rson].val);
}
//合并左右儿子的信息

void pushdown(int root){
	if(!tree[root].lzy) return;
	tree[lson].val-=tree[root].lzy;
	tree[rson].val-=tree[root].lzy;
	tree[lson].lzy+=tree[root].lzy;
	tree[rson].lzy+=tree[root].lzy;
	tree[root].lzy=0;
}
//懒标记下传

void build(int root,int l,int r){
	tree[root].lzy=0;
	if(l==r){
		tree[root].val=f[l];
		return;
	}
	int mid=l+r>>1;
	build(lson,l,mid);
	build(rson,mid+1,r);
	pushup(root);
}
//建树

int query(int root,int l,int r,int L,int R){
	if(L>r || R<l) return INT_MAX;
	if(L<=l && R>=r) return tree[root].val;
	if(r>l) pushdown(root);
	int mid=l+r>>1,res=INT_MAX;
	if(L<=mid) res=min(res,query(lson,l,mid,L,R));
	if(R>mid) res=min(res,query(rson,mid+1,r,L,R));
	return res;
}
//查询最小值

void update(int root,int l,int r,int L,int R,int x){
	if(L>r || R<l) return;
	if(L<=l && R>=r){
		tree[root].val-=x,tree[root].lzy+=x;
		return;
	}
	if(r>l) pushdown(root);
	int mid=l+r>>1;
	if(L<=mid) update(lson,l,mid,L,R,x);
	if(R>mid) update(rson,mid+1,r,L,R,x);
	pushup(root);
}
//区间减操作

int main(){
	ios::sync_with_stdio(false),cin.tie(nullptr);
	cin>>n>>k;
	for(int i=1;i<=n;i++){
		int x;
		cin>>x;
		f[x]++; //桶数组f存每个数出现的次数
		maxn=max(maxn,x); //maxn为输入数据的最大值
	}
	build(1,1,maxn);
	long long ans=0; //一定一定要开long long,不然会爆
	for(int x=maxn-k;x>k;x--){ //贪心,限定枚举范围
		int m=query(1,1,maxn,x-k,x+k); 
		if(!m) continue; //若区间内有数值不存在则跳过
		ans+=1LL*m*x; //否则做m次操作,获得m*x点收益
		update(1,1,maxn,x-k,x+k,m); //将当前区间内所有数都减去m
	}
	cout<<ans;
	return 0;
}

时间复杂度: O(n+max⁡ailog⁡max⁡ai)O(n+\max a_i \log\max a_i )

空间复杂度: O(max⁡ai)O(\max a_i)

原文