题解:P17246 【Gensokyo OI Round 2】长夜梦难却
ProjectMili · · 个人记录
本蒟蒻刚学线段树不久来打比赛结果赛时被硬控2h只骗到了20分。
题目要求最大收益,考虑贪心。
对于每次操作,
附上扯淡简略贪心正确性证明:
每次操作消耗序列中值为
那么问题来了:我们需要一种能够快速执行区间修改和最值查询的数据结构。
没错,就是线段树。(用来做这道题的是支持区间减和最小值查询的线段树,维护的是序列
:::success[AC代码]
#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;
}
时间复杂度:
空间复杂度: