洛谷P3870

Gong Jin Lv6

手打代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<bits/stdc++.h>

#define pl p<<1
#define pr p<<1|1
#define ll long long

using namespace std;

const int N=1e5+5;
ll n,m,a[N],w[N<<2],lazy[N<<2];

void pushup(ll p){
w[p]=w[pl]+w[pr];
}

void pushdown(ll p,ll l,ll r){
if(lazy[p]==0)return;
lazy[pl]=!lazy[pl];
lazy[pr]=!lazy[pr];
ll mid=(l+r)>>1;
w[pl]=(mid-l+1)-w[pl];
w[pr]=(r-mid)-w[pr];
lazy[p]=0;
}


//void build(ll p,ll l,ll r){
// if(l==r){
// w[p]=0;
// return;
// }
// ll mid=l+r>>1;
// build(pl,l,mid);
// build(pr,mid+1,r);
// pushup(p);
//}

void updata(ll p,ll l,ll r,ll L,ll R){
if(r<L||l>R) return;
if(l>=L&&r<=R){
lazy[p]=!lazy[p];
w[p]=r-l+1-w[p];
return;
}
pushdown(p,l,r);
ll mid=l+r>>1;
updata(pl,l,mid,L,R);
updata(pr,mid+1,r,L,R);
pushup(p);
}
ll query(ll p,ll l,ll r,ll L,ll R){
if(r<L||l>R)return 0;
if(l>=L&&r<=R)return w[p];
ll mid=l+r>>1;
pushdown(p,l,r);
return query(pl,l,mid,L,R)+query(pr,mid+1,r,L,R);
}

int main(){
ll op,k,x,y;
cin>>n>>m;
// for(int i=1;i<=n;i++) cin>>a[i];
// build(1,1,n);
for(int i=1;i<=m;i++){
cin>>op>>x>>y;
if(op==0){
updata(1,1,n,x,y);
}
if(op==1){
cout<<query(1,1,n,x,y)<<endl;
}
}
return 0;
}

AI分析

线段树维护区间翻转和区间求和。序列初始全为 0,操作 0 把一段区间内的 0 变 1、1 变 0,操作 1 询问一段区间内 1 的个数。代码用 lazy 标记表示该区间的翻转状态:下推时把标记异或给两个儿子,并用区间长度减去原来的 1 的个数,得到翻转后新的 1 的个数。这个公式是本题的核心,因为翻转并不会改变区间长度,只是把 0 和 1 互换。修改和查询的递归结构与普通线段树一致,完全覆盖就更新或返回。整体 O(m log n),是练习异或标记的经典题目。

注意懒标记只需要一个布尔值,多次翻转会相互抵消,用异或维护即可。题目初始全为 0,省去了建树步骤,这也提醒我们按需裁剪代码。

  • 标题: 洛谷P3870
  • 作者: Gong Jin
  • 创建于 : 2025-03-08 10:33:26
  • 更新于 : 2026-11-22 10:13:46
  • 链接: https://blog.zymc.net/2025/03/08/洛谷/洛谷P3870/
  • 版权声明: 版权所有 © Gong Jin,禁止转载。
评论
目录
洛谷P3870