题解:AT_abc287_g [ABC287G] Balance Update Query
算法标签
权值线段树、离散化、离线处理。
题目大意
有 种卡片,每种卡片有两种属性:价值 和数目 (分别对应题目中的得分和可用张数),要求支持 种操作:
1 x y:将 的数值改为 。2 x y:将 的数值改为 。3 x:输出在所有卡片中选择 张卡片的最大价值。如果 ,则输出 。
解题思路
这里提供一个权值线段树的解法。
我们可以将这 种卡牌按 的值分为若干堆。接着对 种操作分别讨论:
操作
的数值改为 ,相当于第 堆的所有卡牌的权值改为 ,修改后权值为 的堆的卡牌数量少了 张,权值为 的堆的卡牌数量多了 张,其余不变。于是操作 可以转换成两个单点修改操作,时间复杂度 。
操作
直接单点修改,时间复杂度 。
操作
由贪心算法可知,要使答案最大,需选取价值最大的 张卡牌,对应到权值线段树上就是最右边的 张卡牌,递归二分搜索线段树即可。线段树维护区间价值和。时间复杂度依旧是 。
总体复杂度分析
共有 次询问,单次询问的时间复杂度为 ,所以总体时间复杂度为 ;空间复杂度是 ,可以通过本题。
具体实现
首先,需要维护一棵权值线段树,并维护每个节点的卡牌数量辅助区间价值和的计算,查询也较容易实现。
其次, 的值域在 左右,而实际有效的数最多 ,所以需要离线使用离散化。
然后,对于操作 和操作 ,单点更新完后需要将对应的 数组和 数组更新,否则下次更新会发生错误。对于操作 ,还需特判一下根节点的卡牌数量是否 。
最后,注意要开long long。
参考代码
AC code
#include<bits/stdc++.h>
using namespace std;
const int MAXN=2e5+10;
struct Query{
int operation,x,y;
};
struct NODE{
int l,r,cnt;
long long sum;
};
NODE tree[MAXN*8];
Query queries[MAXN];
int a[MAXN],b[MAXN],c[MAXN*2],d[MAXN*2];
int n,tot=0,q,m=0;
void push_up(int rt){
tree[rt].cnt=tree[rt*2].cnt+tree[rt*2+1].cnt;
tree[rt].sum=tree[rt*2].sum+tree[rt*2+1].sum;
return;
}
void build(int rt,int l,int r){
tree[rt].l=l;
tree[rt].r=r;
if(l==r){
tree[rt].cnt=0;
tree[rt].sum=0LL;
return;
}
int mid=(l+r)>>1;
build(rt*2,l,mid);
build(rt*2+1,mid+1,r);
push_up(rt);
return;
}
void upd(int rt,int x,int k){
if(tree[rt].l==tree[rt].r){
tree[rt].cnt+=k;
tree[rt].sum=1LL*d[tree[rt].l]*tree[rt].cnt;
return;
}
int mid=(tree[rt].l+tree[rt].r)>>1;
if(x<=mid){
upd(rt*2,x,k);
}else{
upd(rt*2+1,x,k);
}
push_up(rt);
return;
}
long long qry_sum(int rt,int target){
if(tree[rt].cnt==target){
return tree[rt].sum;
}
if(tree[rt].l==tree[rt].r){
return 1LL*d[tree[rt].l]*target;
}
if(tree[rt*2+1].cnt<target){
return tree[rt*2+1].sum+qry_sum(rt*2,target-tree[rt*2+1].cnt);
}else{
return qry_sum(rt*2+1,target);
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i]>>b[i];
tot++;
c[tot]=a[i];
}
cin>>q;
for(int i=1;i<=q;i++){
int operation,x,y;
cin>>operation>>x;
if(operation==3){
y=-1;
}else{
cin>>y;
}
queries[i]=(Query){operation,x,y};
if(operation==1){
tot++;
c[tot]=y;
}
}
sort(c+1,c+tot+1);
for(int i=1;i<=tot;i++){
if(i==1||c[i]!=c[i-1]){
m++;
d[m]=c[i];
}
}
build(1,1,m);
for(int i=1;i<=n;i++){
a[i]=lower_bound(d+1,d+m+1,a[i])-d;
upd(1,a[i],b[i]);
}
for(int i=1;i<=q;i++){
int operation=queries[i].operation,x=queries[i].x,y=queries[i].y;
if(operation==1){
y=lower_bound(d+1,d+m+1,y)-d;
upd(1,a[x],-b[x]);
upd(1,y,b[x]);
a[x]=y;
}else if(operation==2){
upd(1,a[x],y-b[x]);
b[x]=y;
}else{
if(x>tree[1].cnt){
cout<<"-1";
}else{
cout<<qry_sum(1,x);
}
cout<<endl;
}
}
return 0;
}