这是本人的代码(很经典的线段树写法):
//杉月
#include<bits/stdc++.h>
#define N 1000005
//#define int long long
typedef long long LL;
using namespace std;
const LL Inf=1e18;
int n,q;
LL w[4*N],ladd[4*N],lset[4*N],a[N];
void pushup(int u){
w[u]=max(w[2*u],w[2*u+1]);
return;
}
bool in(int l,int r,int L,int R){
return (l>=L&&r<=R);
}
bool unin(int l,int r,int L,int R){
return (R<l||L>r);
}
void mark(int u,LL x,int type){
if(type==1){
ladd[u]=0;lset[u]=x;w[u]=x;
}else{
if(lset[u]==Inf) ladd[u]+=x;
else lset[u]+=x;
w[u]+=x;
}
}
void pushdown(int u){
if(lset[u]==Inf){
mark(2*u,ladd[u],2);
mark(2*u+1,ladd[u],2);
ladd[u]=0;
}else{
mark(2*u,lset[u],1);
mark(2*u+1,lset[u],1);
lset[u]=Inf;
}
return;
}
void build(int u,int l,int r){
lset[u]=Inf;
if(l==r){
w[u]=a[l];
return;
}
int mid=(l+r)>>1;
build(2*u,l,mid);
build(2*u+1,mid+1,r);
pushup(u);
return;
}
void change(int u,int l,int r,int L,int R,LL x,int type){
if(in(l,r,L,R)){
mark(u,x,type);
}else{
if(!unin(l,r,L,R)){
int mid=(l+r)>>1;
pushdown(u);
change(2*u,l,mid,L,R,x,type);
change(2*u+1,mid+1,r,L,R,x,type);
pushup(u);
}
}
return;
}
LL query(int u,int l,int r,int L,int R){
if(in(l,r,L,R)){
return w[u];
}else{
if(!unin(l,r,L,R)){
int mid=(l+r)>>1;
pushdown(u);
return max(query(2*u,l,mid,L,R),query(2*u+1,mid+1,r,L,R));
}else{
return -Inf;
}
}
}
int main(){
//freopen("edit2.in","r",stdin);
//freopen("edit2.out","w",stdout);
ios::sync_with_stdio(0);
cin.tie();cout.tie();
cin>>n>>q;
for(int i=1;i<=n;i++){
cin>>a[i];
}
build(1,1,n);
for(int i=1;i<=q;i++){
int op,l,r;
LL x;
cin>>op;
if(op==1){
cin>>l>>r>>x;
change(1,1,n,l,r,x,1);
}
if(op==2){
cin>>l>>r>>x;
change(1,1,n,l,r,x,2);
}
if(op==3){
cin>>l>>r;
cout<<query(1,1,n,l,r)<<endl;
}
}
return 0;
}
为什么使用O2优化会超时#10呢?把O2关了就不超时了?