P3870 [TJOI2009] 开关
P3870 [TJOI2009] 开关
TJOI2009] 开关 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
线段树
维护区间和,区间异或
区间异或可视为 区间和 = 区间长度 - 区间和
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
int n, m;
struct Node
{
int l, r;
int sum, lazy;
}tr[N*4];
void pushup(int u)
{
tr[u].sum = tr[u << 1].sum + tr[u << 1 | 1].sum;
}
void pushdown(int u)
{
Node &root = tr[u], &left = tr[u << 1], &right = tr[u << 1 | 1];
if (root.lazy)
{
left.sum = left.r - left.l + 1 - left.sum;
right.sum = right.r - right.l + 1 - right.sum;
left.lazy ^= 1;
right.lazy ^= 1;
root.lazy = 0;
}
}
void build(int u, int l, int r)
{
if (l == r)
{
tr[u] = {l, r, 0, 0};
return;
}
tr[u] = {l, r};
int mid = l + r >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
pushup(u);
}
void modify(int u, int l, int r)
{
if (tr[u].l >= l && tr[u].r <= r)
{
tr[u].lazy ^= 1;
tr[u].sum = tr[u].r - tr[u].l + 1 - tr[u].sum;
return;
}
int mid = tr[u].l + tr[u].r >> 1;
pushdown(u);
if (l <= mid)
modify(u << 1, l, r);
if (r > mid)
modify(u << 1 | 1, l, r);
pushup(u);
}
int query(int u, int l, int r)
{
if (tr[u].l >= l && tr[u].r <= r)
{
return tr[u].sum;
}
int mid = tr[u].l + tr[u].r >> 1;
pushdown(u);
int ans = 0;
if (l <= mid)
ans = query(u << 1, l, r);
if (r > mid)
ans += query(u << 1 | 1, l, r);
pushup(u);
return ans;
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> n >> m;
build(1, 1, n);
while(m--)
{
int c, a, b;
cin >> c >> a >> b;
if (c == 0)
modify(1, a, b);
else
cout << query(1, a, b) << endl;
}
return 0;
}