ABC467F 贪心+线段树+离散化
题目传送门
洛谷,AtCoder。
背景
这次 ABC 被 A 和 D 浮点精度创飞了……
正文
::::info[分析] 作为蒟蒻,许多神犇关于这道题第一步贪心的证明我真的看不懂啊(甚至还有没有证明的?),于是我只能用更通俗的方法解释啦!
感性推理:每封邮件,我们都有一个写信需要时间,和一个回复需要的时间,由于所有邮件都要写,而且高桥不是八爪鱼,任意时刻只能有一封信在写,所以写信时间并不影响最终答案。那怎么才能快速得到所有回信呢?当然回信慢的要在前面。
| 按照回信所需时间降序排序(但代码为了实现简单,我使用了升序,那细节上要反一下)。 |
|---|
| ::::info[转换] |
| 这里很麻烦的一点就是后面还要修改一些值。考虑先将所有的回信所需时间离散化(包括后面要修改的),使用线段树维护。 |
每个叶子代表一个回信所需时间,每个回信所需时间都是一个叶子(如果有相同的,共享一个叶子)。
线段树维护两个值,一个是这一段区间写信所需的总时间,另一个是不考虑别的区间,本区间内,写并收到所有回信所需最少时间。
| 最后,关于值的修改,我们可以直接将叶子结点进行加减。 |
|---|
| ::::success[实现&AC Code] |
| ```cpp |
| #include<iostream> |
| #include<algorithm> |
| #define LL long long |
| #define F(i,k,n) for(int i=(k);i<=(n);++i) |
| #define RF(i,k,n) for(int i=(k);i>=(n);--i) |
| #define ls (p<<1) |
| #define rs (p<<1) |
| using namespace std; |
| struct node{ |
| int a; |
| int b; |
| }sct[100005]; |
| struct QS{ |
| int op; |
| int x; |
| int y; |
| }qs[100005]; |
| int lsh[200005]; |
| LL aa[200005]; |
| int ad; |
| int fd(int x){ |
| return lower_bound(lsh+1,lsh+ad+1,x)-lsh; |
| } |
| struct SMT{ |
| int l; |
| int r; |
| LL suma; |
| LL ans; |
| }tr[800005]; |
| void push_up(int p){ |
| tr[p].suma=tr[ls].suma+tr[rs].suma; |
| tr[p].ans=max(tr[rs].ans,tr[rs].suma+tr[ls].ans); |
| return; |
| } |
| void build(int l,int r,int p=1){ |
| tr[p].l=l; |
| tr[p].r=r; |
| if(l==r){ |
| tr[p].suma=aa[l]; |
| if(tr[p].suma>0) |
| tr[p].ans=aa[l]+lsh[l]; |
| else |
| tr[p].ans=-4e18;//这里不能赋0,不然push_up还会错 |
| return; |
| } |
| build(l,(l+r)>>1,ls); |
| build(((l+r)>>1)+1,r,rs); |
| push_up(p); |
| return; |
| } |
| void update(int x,LL y,int p=1){ |
| if(tr[p].l==tr[p].r){ |
| tr[p].suma+=y; |
| if(tr[p].suma==0) |
| tr[p].ans=-4e18; |
| else |
| tr[p].ans=tr[p].suma+lsh[tr[p].l]; |
| return; |
| } |
| if(x<=tr[ls].r) |
| update(x,y,ls); |
| else |
| update(x,y,rs); |
| push_up(p); |
| return; |
| } |
| signed main(){ |
| ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); |
| int n,q; |
| cin>>n>>q; |
| F(i,1,n){ |
| cin>>sct[i].a; |
| } |
| F(i,1,n){ |
| cin>>sct[i].b; |
| lsh[i]=sct[i].b; |
| } |
| ad=n; |
| F(i,1,q){ |
| cin>>qs[i].op>>qs[i].x>>qs[i].y; |
| if(qs[i].op==2) |
| lsh[++ad]=qs[i].y; |
| } |
| sort(lsh+1,lsh+ad+1); |
| ad=unique(lsh+1,lsh+ad+1)-lsh-1;//别忘了获取当前长度 |
| F(i,1,n){ |
| aa[fd(sct[i].b)]+=sct[i].a; |
| } |
| build(1,ad); |
| F(i,1,q){ |
| if(qs[i].op==1){ |
| update(fd(sct[qs[i].x].b),qs[i].y-sct[qs[i].x].a); |
| sct[qs[i].x].a=qs[i].y; |
| }else{ |
| update(fd(sct[qs[i].x].b),-sct[qs[i].x].a); |
| update(fd(qs[i].y),sct[qs[i].x].a); |
| sct[qs[i].x].b=qs[i].y; |
| } |
| cout<<tr[1].ans<<'\n'; |
| } |
| return 0; |
| } |
[提交记录](https://atcoder.jp/contests/abc467/submissions/77670260)。
::::