BZOJ 1935 园丁的烦恼
题解:如果 x 和 y 足够小的话, 我们就可以用2维树状数组去单点修改,区间查询去计算答案。但是现在 x 和 y 都足够大, 我们没办法去这样操作。
现在我们转换思路,按 x 为第一权重, y 为第二权重去排序, 这样我们就可以只用一颗树状数组去维护 x到当前为止y的数目。
然后对于查询来说,我们把一个矩阵的查询分为4次查询, 用差分的思想维护。还是和树状数组2维查询区间的时候,对于一个矩阵(x1,y1)(左下角的点) (x2,y2)(右上角的点), 我们把这个查询拆成4个点
即到(x1-1,y1-1),(x2,y2)为止所出现的点的数目加到对应的答案里,然后删掉到(x1-1,y2), (x2,y1-1)为止出现的数目。这样对于这个矩阵我们就计算完了答案。
代码:
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define Fopen freopen("_in.txt","r",stdin); freopen("_out.txt","w",stdout); 4 #define LL long long 5 #define ULL unsigned LL 6 #define fi first 7 #define se second 8 #define pb emplace_back 9 #define lson l,m,rt<<1 10 #define rson m+1,r,rt<<1|1 11 #define lch(x) tr[x].son[0] 12 #define rch(x) tr[x].son[1] 13 #define max3(a,b,c) max(a,max(b,c)) 14 #define min3(a,b,c) min(a,min(b,c)) 15 typedef pair<int,int> pll; 16 const int inf = 0x3f3f3f3f; 17 const LL INF = 0x3f3f3f3f3f3f3f3f; 18 const LL mod = (int)1e9+7; 19 const int N = 3e6 + 100; 20 const int M = 1e7 + 100; 21 int tree[M]; 22 inline int lowbit(int x){ 23 return x & (-x); 24 } 25 void Add(int x){ 26 for(int i = x; i < M; i+=lowbit(i)) 27 tree[i] += 1; 28 } 29 int Query(int x){ 30 int ret = 0; 31 for(int i = x; i; i -= lowbit(i)){ 32 ret += tree[i]; 33 } 34 return ret; 35 } 36 int ans[N]; 37 struct Node{ 38 int x, y, op, id; 39 bool operator< (const Node & node) const{ 40 if(x != node.x) return x < node.x; 41 if(y != node.y) return y < node.y; 42 return op < node.op; 43 } 44 }A[N]; 45 int tot = 0; 46 void nownode(int x, int y, int op, int id){ 47 tot++; 48 //if(id) cout << x << " " << y << " " << op << " " << id << endl; 49 A[tot].x = x; 50 A[tot].y = y; 51 A[tot].op = op; 52 A[tot].id = id; 53 } 54 int main(){ 55 int n, m, x, y, x1, y1, id, op; 56 scanf("%d%d", &n, &m); 57 for(int i = 1; i <= n; i++){ 58 scanf("%d%d", &x, &y); 59 ++x; 60 ++y; 61 nownode(x, y, 0, 0); 62 } 63 for(int i = 1; i <= m; i++){ 64 scanf("%d%d%d%d", &x, &y, &x1, &y1); 65 ++x; ++y; ++x1; ++y1; 66 nownode(x1, y1, 1, i); 67 nownode(x-1, y-1, 1, i); 68 nownode(x-1, y1, 2, i); 69 nownode(x1, y-1, 2, i); 70 } 71 sort(A+1, A+1+tot); 72 for(int i = 1; i <= tot; i++){ 73 y = A[i].y;id = A[i].id, op = A[i].op; 74 //cout << y << " " << id << " " << op << endl; 75 if(!op) Add(y); 76 else if(op == 1) ans[id] += Query(y); 77 else ans[id] -= Query(y); 78 } 79 for(int i = 1; i <= m; i++){ 80 printf("%d\n", ans[i]); 81 } 82 return 0; 83 }