看到题目很容易想到线段树,关键在于怎么维护以及维护哪些东西。
首先肯定要维护区间盘子内章鱼烧数量的最大值。但是, 操作不能直接给每个区间的最大值都加上 ,需要判断区间内的盘子是否全部朝下,如果是,那么最大值仍保持为 。
因此,我们维护一个变量 ,值为 代表区间内盘子全部朝上, 代表有上有下, 代表全部朝下。 操作区间更新时检查 即可。
接下来考虑 操作。 操作相当于做了两件事:
- 将区间最大值设为 。
- 将区间所有盘子反转。
对于第二件事,我们要再开一个懒标记 记录区间的盘子状态是否被翻转。下放时,如果需要反转,直接使 即可。
注意,第一件事和第二件事不能共用一个懒标记,因为一个代表是否操作过,一个代表操作次数的奇偶性。所以,我们要再开一个懒标记 来处理第一件事。
具体细节可见代码:
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10;
struct Node {
int l,r,type; long long mx,lzy; bool has,flip;
void tag1(long long x) { if(type!=3) mx+=x,lzy+=x; }
void tag2() { has=true,mx=0,lzy=0; }
void tag3() { flip^=1,type=4-type; }
}t[N<<2];
void pushup(int u) {
t[u].mx=max(t[u<<1].mx,t[u<<1|1].mx);
if(t[u<<1].type==1&&t[u<<1|1].type==1) t[u].type=1;
else if(t[u<<1].type==3&&t[u<<1|1].type==3) t[u].type=3;
else t[u].type=2;
}
void build(int u,int l,int r) {
t[u].l=l,t[u].r=r;
if(l==r) {
t[u].type=1;
return;
}
int m=(l+r)>>1;
build(u<<1,l,m),build(u<<1|1,m+1,r);
pushup(u);
}
void pushdown(int u) {
if(t[u].has) t[u<<1].tag2(),t[u<<1|1].tag2(),t[u].has=false;
if(t[u].flip) t[u<<1].tag3(),t[u<<1|1].tag3(),t[u].flip=false;
if(t[u].lzy) t[u<<1].tag1(t[u].lzy),t[u<<1|1].tag1(t[u].lzy),t[u].lzy=0;
}
void update1(int u,int l,int r,int x) {
if(l<=t[u].l&&t[u].r<=r) {
t[u].tag1(x);
return;
}
pushdown(u);
if(l<=t[u<<1].r) update1(u<<1,l,r,x);
if(r>=t[u<<1|1].l) update1(u<<1|1,l,r,x);
pushup(u);
}
void update2(int u,int l,int r) {
if(l<=t[u].l&&t[u].r<=r) {
t[u].tag2(),t[u].tag3();
return;
}
pushdown(u);
if(l<=t[u<<1].r) update2(u<<1,l,r);
if(r>=t[u<<1|1].l) update2(u<<1|1,l,r);
pushup(u);
}
long long query(int u,int l,int r) {
if(l<=t[u].l&&t[u].r<=r) return t[u].mx;
pushdown(u);
if(r<=t[u<<1].r) return query(u<<1,l,r);
if(l>=t[u<<1|1].l) return query(u<<1|1,l,r);
return max(query(u<<1,l,r),query(u<<1|1,l,r));
}
int main() {
ios::sync_with_stdio(false),cin.tie(nullptr);
int n,q; cin>>n>>q,build(1,1,n);
while(q--) {
int opt,l,r; cin>>opt>>l>>r;
if(opt==1) {
int x; cin>>x;
update1(1,l,r,x);
}
if(opt==2) update2(1,l,r);
if(opt==3) cout<<query(1,l,r)<<'\n';
}
return 0;
}