“GSS x - Can you answer these queries X ?”系列
2022.11.14
GSS1 - Can you answer these queries I
-
直接线段树
-
这应该是几道题里面最水的一题吧
#include<bits/stdc++.h>
using namespace std;
int n,q;
int a[50005];
struct emm{
int left,right;
int ans,res,prel,prer;
}c[200005];
void push_up(int p){
int l=p*2;
int r=l+1;
c[p].ans=c[l].ans+c[r].ans;
c[p].prel=max(c[l].prel,c[l].ans+c[r].prel);
c[p].prer=max(c[r].prer,c[r].ans+c[l].prer);
c[p].res=max(max(c[l].res,c[r].res),c[l].prer+c[r].prel);
return;
}
void build(int p,int l,int r){
c[p].left=l,c[p].right=r;
if(l==r){
c[p].res=a[l];
c[p].ans=a[l];
c[p].prel=a[l];
c[p].prer=a[l];
return;
}
int mid=(l+r)/2;
build(p*2,l,mid);
build(p*2+1,mid+1,r);
push_up(p);
return;
}
emm find(int p,int l,int r){
if(c[p].left>=l&&c[p].right<=r)return c[p];
if((c[p].left+c[p].right)/2<l)return find(p*2+1,l,r);
if((c[p].left+c[p].right)/2>=r)return find(p*2,l,r);
emm dl=find(p*2,l,r),dr=find(p*2+1,l,r),res;
res.ans=dl.ans+dr.ans;
res.prel=max(dl.prel,dl.ans+dr.prel);
res.prer=max(dr.prer,dr.ans+dl.prer);
res.res=max(max(dl.res,dr.res),dl.prer+dr.prel);
return res;
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
build(1,1,n);
scanf("%d",&q);
while(q--){
int l,r;
scanf("%d%d",&l,&r);
printf("%d\n",find(1,l,r).res);
}
return 0;
}
GSS3 - Can you answer these queries III
- 其实就是
GSS1 - Can you answer these queries I的加强版,多了个修改而已。
#include<bits/stdc++.h>
using namespace std;
int n,q;
int a[50005];
struct emm{
int left,right;
int ans,res,prel,prer;
}c[200005];
void push_up(int p){
int l=p*2;
int r=l+1;
c[p].ans=c[l].ans+c[r].ans;
c[p].prel=max(c[l].prel,c[l].ans+c[r].prel);
c[p].prer=max(c[r].prer,c[r].ans+c[l].prer);
c[p].res=max(max(c[l].res,c[r].res),c[l].prer+c[r].prel);
return;
}
void build(int p,int l,int r){
c[p].left=l,c[p].right=r;
if(l==r){
c[p].res=a[l];
c[p].ans=a[l];
c[p].prel=a[l];
c[p].prer=a[l];
return;
}
int mid=(l+r)/2;
build(p*2,l,mid);
build(p*2+1,mid+1,r);
push_up(p);
return;
}
emm find(int p,int l,int r){
if(c[p].left>=l&&c[p].right<=r)return c[p];
if((c[p].left+c[p].right)/2<l)return find(p*2+1,l,r);
if((c[p].left+c[p].right)/2>=r)return find(p*2,l,r);
emm dl=find(p*2,l,r),dr=find(p*2+1,l,r),res;
res.ans=dl.ans+dr.ans;
res.prel=max(dl.prel,dl.ans+dr.prel);
res.prer=max(dr.prer,dr.ans+dl.prer);
res.res=max(max(dl.res,dr.res),dl.prer+dr.prel);
return res;
}
void change(int p,int l,int y){
if(c[p].right<l||c[p].left>l)return;
if(c[p].right==c[p].left){
c[p].ans=y;
c[p].prel=y;
c[p].prer=y;
c[p].res=y;
return;
}
change(p*2,l,y);
change(p*2+1,l,y);
push_up(p);
return;
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
build(1,1,n);
scanf("%d",&q);
while(q--){
int x,l,r;
scanf("%d%d%d",&x,&l,&r);
if(x==0)change(1,l,r);
else printf("%d\n",find(1,l,r).res);
}
return 0;
}