二维线段树

二维线段树一般用树套树的方式实现,每个外层线段树的节点对应一颗内层线段树,整个线段树存放在一个二维数组中。

二维线段树 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;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值