two-dimensional tree array

Two-dimensional tree arrays are similar to one-dimensional ones, and are divided into two types: single-point update interval query and interval update single-point query

1. Single point update, interval query

add(int x, int y, int d):tree[x][y] += d;

sum(int x, int y): returns the sum of (1,1) to (x, y)

Notice:

Modify the value of a point, num[x][y] += d; call add(x, y, d);

To calculate the sum of the numbers in the region of vertices (x1, y1), (x2, y2), call

sum(x2, y2) – sum(x2, y1 - 1) – sum(x1 – 1, y2) + sum(x1 – 1, y1 - 1); (prefix and idea)

(x, y) to start at (1, 1), (0, 0) will cause infinite loop timeout

 

 1 int lowbit(int x)
 2 {
 3     return x & (-x);
 4 }
 5 //修改tree[x][y] += d;
 6 void add(int x, int y, int d)
 7 {
 8     for(int i = x; i <= n; i += lowbit(i))
 9     {
10         for(int j = y; j <= n; j += lowbit(j))
11         {
12             tree[i][j] += d;
13         }
 14      }
 15  }
 16  // Sum of numbers from (1,1) to (x, y) 
17 ll sum( int x, int y)
 18  {
 19      ll ans = 0 ;
 20      for ( int i = x; i > 0 ; i -= lowbit(i)) // Equal to 0 will loop infinitely 
21      {
 22          for ( int j = y; j > 0 ; j -= lowbit(j))
 23          {
 24              ans += tree[i] [j];
 25          }
 26     }
 27      return years;
28 }

 

2. Interval update, single-point query

add(int x, int y, int d): add d to (1,1) to (x,y)

sum(int x, int y): returns the value of the point (x, y)

Notice:

1. Area [x1, y1] to [x2, y2] plus d:

 

transfer:              

    add(x2, y2, 1);

 

    add(x1 - 1, y1 - 1, 1);

 

    add(x2, y1 - 1, -1);

    add(x1 - 1, y2, -1);

 

2. Query a point value sum(x, y);

 

 1 int lowbit(int x)
 2 {
 3     return x&(-x);
 4 }
 5 int sum(int x, int y)
 6 {
 7     int ret = 0;
 8     for(int i = x; i <= n; i += lowbit(i))
 9     {
10         for(int j = y; j <= n; j += lowbit(j))
11             ret += tree[i][j];
12     }
13     return ret;
14 }
15 void add(int x, int y, int d)
16 {
17     for(int i = x; i > 0; i -= lowbit(i))
18     {
19         for(int j = y; j > 0; j -= lowbit(j))
20             tree[i][j] += d;
21     }
22 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324781574&siteId=291194637