Luogu2574 XOR的艺术 (分块)

本是要练线段树的,却手贱打了个分块

//#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define R(a,b,c) for(register int  a = (b); a <= (c); ++ a)
#define nR(a,b,c) for(register int  a = (b); a >= (c); -- a)
#define Max(a,b) ((a) > (b) ? (a) : (b))
#define Min(a,b) ((a) < (b) ? (a) : (b))
#define Fill(a,b) memset(a, b, sizeof(a))
#define Abs(a) ((a) < 0 ? -(a) : (a))
#define Swap(a,b) a^=b^=a^=b
#define ll long long

#define ON_DEBUG

#ifdef ON_DEBUG

#define D_e_Line printf("

----------

")
#define D_e(x)  cout << #x << " = " << x << endl
#define Pause() system("pause")
#define FileOpen() freopen("inn.txt","r",stdin);

#else

#define D_e_Line ;
#define D_e(x)  ;
#define Pause() ;
#define FileOpen() ;

#endif

struct ios{
    template<typename ATP>ios& operator >> (ATP &x){
        x = 0; int f = 1; char c;
        for(c = getchar(); c < '0' || c > '9'; c = getchar()) if(c == '-')  f = -1;
        while(c >= '0' && c <= '9') x = x * 10 + (c ^ '0'), c = getchar();
        x*= f;
        return *this;
    }
}io;
using namespace std;

const int N = 200007;

int n;

int blockSize, block[N];
int ans[N], a[N], tag[N];
inline void Updata(int l, int r){
	int minn = Min(r, blockSize * block[l]);
	R(i,l,minn){
		a[i] ^= 1;
		ans[block[i]] += ((a[i] ^ tag[block[i]]) == 1) - ((a[i] ^ tag[block[i]]) == 0);
	}
	if(block[l] != block[r]){
		R(i,(block[r] - 1) * blockSize + 1, r){
			a[i] ^= 1;
			ans[block[i]] += ((a[i] ^ tag[block[i]]) == 1) - ((a[i] ^ tag[block[i]]) == 0);
		}
	}
	R(i,block[l] + 1, block[r] - 1){
		ans[i] = blockSize - ans[i];
		tag[i] ^= 1;
	}
}
inline int Query(int l, int r){
	int sum = 0;
	int minn = Min(r, blockSize * block[l]);
	R(i,l,minn){
		sum += a[i] ^ tag[block[i]];
	}
	if(block[l] != block[r]){
		R(i,(block[r] - 1) * blockSize + 1, r){
			sum += a[i] ^ tag[block[i]];
		}
	}
	R(i,block[l] + 1, block[r] - 1){
		sum += ans[i];
	}
	return sum;
}

int main(){
	int m;
	io >> n >> m;
	blockSize = sqrt(n);
	R(i,1,n){
		scanf("%1d", a + i);
		block[i] = (i - 1) / blockSize + 1;
		ans[block[i]] += (a[i] == 1);
	}
	
	while(m--){
		int opt, l ,r;
		io >> opt >> l >> r;
		if(opt == 0){
			Updata(l, r);
		}
		else{
			printf("%d
", Query(l, r));
		}
	}
	
	return 0;
}
/*
10 6
1011101001
0 2 4
1 1 5
0 3 7
1 1 10
0 1 4
1 2 6

0 0 0 0 0 1 0 0 0 1
*/

原文地址:https://www.cnblogs.com/bingoyes/p/11233540.html