CF992E 题解
传送门 qwq
线段树题解。
思路还算可以,重要之处在于意识到一种看似暴力的做法由于某些性质而变得正确。
首先想最原始的暴力。直接维护原数组
先考虑这样一件事:对于所有的
考虑优化。由于涉及到大量区间的操作,我们不妨建立线段树维护
再想如何进行修改操作。我们假设把
敲完题解了 rmj 还处于爆炸状态,但是在 CF 上已经通过,代码可以保证正确。
代码:
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n,m;
int read(){
int ss=0,ww=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-')
ww=-1;
ch=getchar();
}
while(ch>='0'&&ch<='9'){
ss=ss*10+ch-'0';
ch=getchar();
}
return ss*ww;
}
const int N=200010;
int a[N],s[N];
struct ST{
int tag;
int maxx;
}st[N*4];
void update(int root,int l,int r){
st[root].maxx=max(st[root*2].maxx,st[root*2+1].maxx);
}
void push_down(int root,int l,int r){
int k=st[root].tag;
st[root].tag=0;
int mid=(l+r)/2;
st[root*2].tag+=k;
st[root*2+1].tag+=k;
st[root*2].maxx+=k;
st[root*2+1].maxx+=k;
}
void build(int root,int l,int r){
if(l==r){
st[root].maxx=a[l]-s[l-1];
return;
}
int mid=(l+r)/2;
build(root*2,l,mid);
build(root*2+1,mid+1,r);
update(root,l,r);
}
void add(int root,int l,int r,int x,int y,int k){
if(l>=x&&r<=y){
st[root].maxx+=k;
st[root].tag+=k;
return;
}
int mid=(l+r)/2;
if(st[root].tag)
push_down(root,l,r);
if(mid>=x)
add(root*2,l,mid,x,y,k);
if(mid+1<=y)
add(root*2+1,mid+1,r,x,y,k);
update(root,l,r);
}
int res;
void ask(int root,int l,int r){
if(res!=-1)
return;
if(l==r){
if(st[root].maxx==0)
res=l;
return;
}
int mid=(l+r)/2;
if(st[root].tag)
push_down(root,l,r);
if(st[root*2].maxx>=0)
ask(root*2,l,mid);
if(st[root*2+1].maxx>=0)
ask(root*2+1,mid+1,r);
}
signed main(){
n=read();
m=read();
for(int i=1;i<=n;i++){
a[i]=read();
s[i]=a[i]+s[i-1];
}
build(1,1,n);
for(int i=1;i<=m;i++){
int x,k;
x=read();
k=read();
int y=k-a[x];
a[x]=k;
add(1,1,n,x,x,y);
if(x!=n)
add(1,1,n,x+1,n,-y);
res=-1;
ask(1,1,n);
printf("%lld\n",res);
}
return 0;
}