Guest User

2D SegTree

a guest
Jun 14th, 2015
332
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <cstdio>
  5. #include <queue>
  6. #include <stack>
  7. #include <utility>
  8.  
  9. using namespace std;
  10. const int MAXN = 40485880;
  11.  
  12. int segTree[MAXN] = {0};
  13.  
  14. class SegmentTree{
  15. public:
  16.     void update(int node, int a1, int b1, int a2, int b2, int x, int y, int A){
  17.         if(x < a1 || x > a2 || y < b1 || y > b2){
  18.             return;
  19.         }
  20.         if(x == a1 && y == b1 && x == a2 && y == b2){
  21.             segTree[node] += A;
  22.             return;
  23.         }
  24.         update(4 * node, a1, b1, (a1 + a2) / 2, (b1 + b2) / 2, x, y, A);
  25.         update(4 * node + 1, a1, (b1 + b2) / 2 + 1, (a1 + a2) / 2, b2, x, y, A);
  26.         update(4 * node + 2, (a1 + a2) / 2 + 1, b1, a2, (b1 + b2) / 2, x, y, A);
  27.         update(4 * node + 3, (a1 + a2) / 2 + 1, (b1 + b2) / 2 + 1, a2, b2, x, y, A);
  28.         segTree[node] = segTree[4 * node] +
  29.                         segTree[4 * node + 1] +
  30.                         segTree[4 * node + 2] +
  31.                         segTree[4 * node + 3];     
  32.     }
  33.     int query(int node, int a1, int b1, int a2, int b2,
  34.         int x, int y, int xx, int yy){
  35.  
  36.         if(a2 < x || b2 < y || a1 > xx || b1 > yy){
  37.             return 0;
  38.         }
  39.  
  40.         if(x <= a1  && y <= b1 && a2 <= xx && b2 <= yy){
  41.             return segTree[node];
  42.         }
  43.  
  44.         int q1, q2, q3, q4;
  45.         q1 = query(4 * node, a1, b1, (a1 + a2) / 2, (b1 + b2) / 2, x, y, xx, yy);
  46.         q2 = query(4 * node + 1, a1, (b1 + b2) / 2 + 1, (a1 + a2) / 2, b2, x, y, xx, yy);
  47.         q3 = query(4 * node + 2, (a1 + a2) / 2 + 1, b1, a2, (b1 + b2) / 2, x, y, xx, yy);
  48.         q4 = query(4 * node + 3, (a1 + a2) / 2 + 1, (b1 + b2) / 2 + 1, a2, b2, x, y, xx, yy);
  49.         return q1 + q2 + q3 + q4;      
  50.     }
  51. };
  52.  
  53. int main(){
  54.     ios::sync_with_stdio(false);
  55.     cin.tie(0);
  56.     cout.tie(0);
  57.     int op, s, x, y, A, l, b, r, t;
  58.  
  59.     //scanf("%d%d", &op, &s);
  60.     cin >> op >> s;
  61.     SegmentTree ST;
  62.  
  63.     while(1){
  64.         cin >> op;
  65.         if(op == 3) break;
  66.         if(op == 1){
  67.             cin >> x >> y >> A;
  68.             ST.update(1, 0, 0, s - 1, s - 1, x, y, A);
  69.         }else{
  70.             cin >> l >> b >> r >> t;
  71.             int w = ST.query(1, 0, 0, s - 1, s - 1, l, b, r, t);
  72.             cout << w << "\n";
  73.         }
  74.     }
  75.     return 0;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment