problem Iahub and Xors
题目大意
一个n*n的矩阵,要求支持两种操作。
操作1:将一个子矩阵的所有值异或某个数。
操作2:询问某个子矩阵的所以值的异或和。
解题分析
由于异或的特殊性,可以用二维树状数组来维护。
因为同一个值只有异或奇数次才有效,因此若单点修改某个点,那么其影响的点为与其行和列奇偶性相同的点,故可以开4个二维树状数组来维护。
如果是区间修改x1,y1,x2,y2,则只需单点修改(x1,y1)、(x1,y2+1)、(x2+1,y2)、(x2+1,y2+1)
如果是区间询问x1,y1,x2,y2,则答案为(x2,y2)^(x1-1,y1-1)^(x1-1,y2)^(x2,y1-1)
参考程序
二维树状数组
1 #include <map> 2 #include <set> 3 #include <stack> 4 #include <queue> 5 #include <cmath> 6 #include <ctime> 7 #include <string> 8 #include <vector> 9 #include <cstdio> 10 #include <cstdlib> 11 #include <cstring> 12 #include <cassert> 13 #include <iostream> 14 #include <algorithm> 15 #pragma comment(linker,"/STACK:102400000,102400000") 16 using namespace std; 17 18 #define N 1008 19 #define M 50008 20 #define LL long long 21 #define lson l,m,rt<<1 22 #define rson m+1,r,rt<<1|1 23 #define clr(x,v) memset(x,v,sizeof(x)); 24 #define bitcnt(x) __builtin_popcount(x) 25 #define rep(x,y,z) for (int x=y;x<=z;x++) 26 #define repd(x,y,z) for (int x=y;x>=z;x--) 27 const int mo = 1000000007; 28 const int inf = 0x3f3f3f3f; 29 const int INF = 2000000000; 30 /**************************************************************************/ 31 32 struct Binary_Indexd_Tree{ 33 LL a[2][2][N][N]; 34 int n; 35 void init(int x) 36 { 37 n=x; 38 clr(a,0); 39 } 40 void update(int x,int y,LL val) 41 { 42 for (int i=x;i<=n+5;i+=i & (-i)) 43 for (int j=y;j<=n+5;j+=j & (-j)) 44 a[x & 1][y & 1][i][j]^=val; 45 } 46 LL query(int x,int y) 47 { 48 LL res=0; 49 for (int i=x;i;i-=i & (-i)) 50 for (int j=y;j;j-=j & (-j)) 51 res^=a[x & 1][y & 1][i][j]; 52 return res; 53 } 54 }T; 55 56 int main() 57 { 58 int n,q; 59 scanf("%d",&n); 60 T.init(n); 61 scanf("%d",&q); 62 rep(i,1,q) 63 { 64 int op,x1,y1,x2,y2; 65 LL val; 66 scanf("%d%d%d%d%d",&op,&x1,&y1,&x2,&y2); 67 if (op==2) 68 { 69 scanf("%I64d",&val); 70 T.update(x1,y1,val); 71 T.update(x1,y2+1,val); 72 T.update(x2+1,y1,val); 73 T.update(x2+1,y2+1,val); 74 } 75 else 76 { 77 LL res=T.query(x2,y2); 78 res^=T.query(x1-1,y1-1); 79 res^=T.query(x1-1,y2); 80 res^=T.query(x2,y1-1); 81 printf("%I64d\n",res); 82 } 83 } 84 }