二维线段树一般用树套树的方式实现,每个外层线段树的节点对应一颗内层线段树,整个线段树存放在一个二维数组中。
二维线段树 poj2155;
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<cctype>
#include<climits>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<string>
#define ll long long
#define MAX 1010
#define INF INT_MAX
#define eps 1e-6
using namespace std;
int c[3*MAX][3*MAX],n;
void update_x(int rooty,int rootx,int L, int R, int x1,int x2){ //更新x方向上的线段树
if (x1 <= L && x2 >= R){
c[rooty][rootx] = !c[rooty][rootx];
return;
}
int mid = L + (R - L) / 2;
if (x2 <= mid) update_x(rooty,rootx*2+1, L, mid, x1, x2);
else if (x1 > mid) update_x(rooty, rootx*2+2, mid+1, R, x1, x2);
else{
update_x(rooty,rootx*2+1, L, mid, x1, mid);
update_x(rooty,rootx*2+2, mid+1, R, mid+1, x2);
}
return;
}
void update_y(int rooty, int L, int R, int x1, int x2, int y1, int y2){ //更新整棵线段树
if (y1 <= L && y2 >= R){
update_x(rooty,0,1,n,x1,x2);
return;
}
int mid = L + (R - L) / 2;
if (y2 <= mid){
update_y(rooty*2+1,L,mid,x1,x2,y1,y2);
}
else if (y1 > mid){
update_y(rooty*2+2,mid+1,R,x1,x2,y1,y2);
}
else{
update_y(rooty*2+1,L,mid,x1,x2,y1,mid);
update_y(rooty*2+2,mid+1,R,x1,x2,mid+1,y2);
}
return;
}
int res;
void query_x(int rooty,int rootx,int L, int R, int x){ //查询x方向上的线段树
if (x >= L && x <= R && c[rooty][rootx] != -1){
res ^= c[rooty][rootx];
}
if (L == R) return;
int mid = L + (R - L) / 2;
if (x <= mid){
query_x(rooty,rootx*2+1,L,mid,x);
}
else {
query_x(rooty,rootx*2+2,mid+1,R,x);
}
}
void query_y(int rooty,int L, int R, int x, int y){ //查询整棵线段树
query_x(rooty,0,1,n,x);
if (L == R) return;
int mid = L + (R-L) / 2;
if (y <= mid){
query_y(rooty*2+1, L, mid, x, y);
}
else {
query_y(rooty*2+2, mid+1, R, x, y);
}
}
int main(){
int T,m;
char s[10];
scanf("%d",&T);
while (T--){
int x,y,x1,x2,y1,y2;
memset(c,0,sizeof(c));
scanf("%d%d",&n,&m);
for (int i=1; i<=m; i++){
scanf("%s",s);
if (s[0] == 'C'){
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
update_y(0,1,n,x1,x2,y1,y2);
}
else{
res = 0;
scanf("%d%d",&x,&y);
query_y(0,1,n,x,y);
printf("%d\n",res);
}
}
if (T) printf("\n");
}
return 0;
}