SHOI2007 园丁的烦恼 离散化+树状数组

传送门

题目大意:多次询问矩阵和,无修改。 n < = 50000 , m < = 500000 n<=50000,m<=500000 n<=50000,m<=500000

题解:这道题提供了一种全新的思路。我以前也常常遇到这种问题,因为数据太小而打了个二维树状数组就过去了。这次的范围比较大,所以要重新考虑算法。

离散化是显然的,把矩形查询变为前缀和查询也是很简单的,但数据范围使我们不能开二维。
那就开一维呗。

如果我们把所有的树和询问都按照y坐标从小到大,相等时x从小到大,都相等时询问在后的规则排一遍序,我们就可以得到一个神奇的序列:每个询问之前的树,y坐标都小于询问的y坐标。这时,我们只需要查询之前的树里x坐标比查询区间小的就行了。

然后就可以只用一维树状数组解决了。

#include
#include
#include
using namespace std;
#define lowbit(x) ((x) & (-x))
const int MAXN = 500001;

int n, m;
int tx[MAXN], ty[MAXN];
int que[MAXN][4];
int bx[MAXN * 3], cntx;
int tree[MAXN];
int Ans[MAXN][5];

struct Node{
	int x, y, opt, num;
	inline bool operator < (const Node &a) const{
		if(y == a.y) return opt < a.opt;
		return y < a.y;
	}
}q[MAXN * 5];
int cnt;

inline int read(){
	int k = 0, f = 1; char ch = getchar();
	while(ch < '0' || ch > '9'){if(ch == '-') f = -1; ch = getchar();}
	while(ch >= '0' && ch <= '9'){k = k*10 + ch - '0'; ch = getchar();}
	return k * f;
}

inline bool cmp(int a, int b){
	return a < b;
}

void add(int _x, int k){
	for(int i = _x; i <= cntx; i += lowbit(i)){
		tree[i] += k;
	}
}

int sum(int _x){
	int ret = 0;
	for(int i = _x; i > 0; i -= lowbit(i)){
		ret += tree[i];
	}
	return ret;
}

//int query(int x_1, int y_1, int x_2, int y_2){
//	return sum(x_2, y_2) - sum(x_1 - 1, y_2) - sum(x_2, y_1 - 1) + sum(x_1 - 1, y_1 - 1);
//}

int Findx(int t){
	int l = 1, r = cntx, mid;
	while(l < r){
		mid = (l + r) >> 1;
		if(bx[mid] >= t){
			r = mid;
		}
		else{
			l = mid + 1;
		}
	}
	return l;
}

int main(){
	n = read(), m = read();
	int Tmp = 0;
	for(int i = 1; i <= n; i++){
		tx[i] = read(), ty[i] = read();
		bx[++Tmp] = tx[i];
	}
	for(int i = 1; i <= m; i++){
		que[i][0] = read(), que[i][1] = read();
		que[i][2] = read(), que[i][3] = read();
		bx[++Tmp] = que[i][0], bx[++Tmp] = que[i][2];
	}
	sort(bx + 1, bx + Tmp + 1, cmp);
	for(int i = 1; i <= Tmp; i++)
		if(i == 1 || bx[i] != bx[i - 1])
			bx[++cntx] = bx[i];
	
	for(int i = 1; i <= n; i++){
		int _x = Findx(tx[i]), _y = ty[i];
		q[++cnt] = (Node){_x, _y, 0, 0};
	}
	
	for(int i = 1; i <= m; i++){
		int _x1 = Findx(que[i][0]), _y1 = que[i][1];
		int _x2 = Findx(que[i][2]), _y2 = que[i][3];
		q[++cnt] = (Node){_x2, _y2, 1, i};
		q[++cnt] = (Node){_x1 - 1, _y2, 2, i};
		q[++cnt] = (Node){_x2, _y1 - 1, 3, i};
		q[++cnt] = (Node){_x1 - 1, _y1 - 1, 4, i};
	}
	sort(q + 1, q + cnt + 1);
	for(int i = 1; i <= cnt; i++){
		
		if(q[i].opt == 0){ //一棵树 
			add(q[i].x, 1);
		}
		else{
			Ans[q[i].num][q[i].opt] = sum(q[i].x);
		}
	}
	
	for(int i = 1; i <= m; i++){
		printf("%d\n", Ans[i][1] - Ans[i][2] - Ans[i][3] + Ans[i][4]);
	}
	
	return 0;
}

你可能感兴趣的:(离散化,树状数组)