[Luogu P2574]XOR的艺术

其实就是一道线段树比板子稍稍难那么一点点的题。

当然这题需要对位运算要有一定深♂入的了解。修改操作要求对一个01串的区间整体xor1,查询操作是查询一个区间内1的个数。显然我们发现这种区间修改区间查询需要拿线段树搞一搞。首先是lazy标记,表示是否对当前区间进行异或操作。因为是01串,异或一次之后再来一次等于没有进行异或操作。所以直接对标记取反比较方便。然后简单模拟一下,结合对位运算的了解我们发现,假如一个区间内有n个1,那么如果对区间整体xor1的话其实是0变成1,1变成0,因此1的个数变成(r - l + 1)- n。运用这些性质就可以拿线段树搞一搞了。

最后,lazy标记不清空害死人啊!!!!!!!!!!!!!我第一次交只有10分,清空标记就过了qwq。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<ctime>
#include<cstdlib>
#include<set>
#include<queue>
#include<vector>
#include<string>
using namespace std;

#define P system("pause");
#define A(x) cout << #x << " " << (x) << endl;
#define AA(x,y) cout << #x << " " << (x) << " " << #y << " " << (y) << endl;
#define ll long long
#define inf 1000000000
#define linf 10000000000000000
#define mem(x) memset(x,0,sizeof(x))

ll read()
{
    ll x = 0,f = 1;
    char c = getchar();
    while(c < '0' || c > '9')
    {
        if(c == '-') f = -1;
        c = getchar();
    }
    while(c >= '0' && c <= '9')
    {
        x = (x << 3) + (x << 1) + c - '0';
        c = getchar();
    }
    return f * x;
}
#define N 200010
#define mid ((l + r) >> 1)
#define ls (x << 1),l,mid
#define rs (x << 1 | 1),mid + 1,r
char s[N];
int tree[N << 2],lazy[N << 2];
void push_up(int x)
{
    tree[x] = tree[x << 1] + tree[x << 1 | 1];
}
void build(int x,int l,int r)
{
    if(l == r)
    {
        tree[x] = s[l] - '0';
        return;
    }
    build(ls);
    build(rs);
    push_up(x);
    return;
}
void push_down(int x,int l,int r)
{
    if(lazy[x])
    {
        lazy[x << 1] ^= 1;
        lazy[x << 1 | 1] ^= 1;
        int len = r - l + 1;
        tree[x << 1] = (len - (len >> 1)) - tree[x << 1];
        tree[x << 1 | 1] = (len >> 1) - tree[x << 1 | 1];
        lazy[x] = 0;
    }
    return;
}
void modify(int x,int l,int r,int p,int q)
{
    if(p <= l && r <= q)
    {
        lazy[x] ^= 1;
        tree[x] = (r - l + 1) - tree[x];
        return;
    }
    push_down(x,l,r);
    if(p <= mid) modify(ls,p,q);
    if(q > mid) modify(rs,p,q);
    push_up(x);
    return;
}
int query(int x,int l,int r,int p,int q)
{
    if(p <= l && r <= q) return tree[x];
    push_down(x,l,r);
    int ret = 0;
    if(p <= mid) ret += query(ls,p,q);
    if(q > mid) ret += query(rs,p,q);
    return ret;
}
int main()
{
    int n = read(),m = read();
    scanf("%s",s + 1);
    build(1,1,n);
    while(m--)
    {
        int op = read(),l = read(),r = read();
        if(op) printf("%d
",query(1,1,n,l,r));
        else modify(1,1,n,l,r);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/lijilai-oi/p/11277034.html