The tree array is to solve the fast update and the sum of the interval of the statistic array, set an array a[1-n], need to calculate the sum of a[m-k], the brute force solution needs O (k-m), if we find sum (1-k) and sum (1-m), then the answer is sum (1-m)-sum (1-k) ;
So how to quickly find sum (1-n), you can consider the direct request, but if we add a condition, need to update immediately, then the use of brute force solution will be problematic, assuming that update a[k], the sum (1-k) to sum (1-n) to update, this is a very time-consuming process.
Here we use a binary idea, and we'll convert decimal to binary for example, like,
C[0001] = a[0001];
C[0010] = a[0010] + a[0001];
C[0011] = a[0011];
C[0100] = a[0100] + a[0011] + a[0010] + a[0001];
C[0101] = a[0101];
C[0110] = a[0110] + a[0101];
C[0111] = a[0111];
C[1000] = a[1000] + a[0111] + a[0110] + a[0101] + a[0100] + a[0011] + a[0010] + a[0001];
Define k as the end of 0 consecutive numbers, can be understood as c[i] = A[i] + ... + a[i-2^k+1].
The process of updating is to update the C[J] related to A[i], for example: i = 0001,j = 0001, 0010, 0100, 1000,i = 0101, j = 0110, 1000; it is not difficult to see the regularity of continuous rounding.
The process of finding sum is to find the c[i of each digit of 1) and, for example:
SUM[1-1111] = c[1111] + c[1110] + c[1100] + c[1000];
C[1111] = a[1111];
C[1110] = a[1110] + a[1101];
C[1100] = a[1100] + a[1011] + a[1010] + a[1001];
C[1000] = a[1000] + a[0111] + a[0110] + a[0101] + a[0100] + a[0011] + a[0010] + a[0001];
Knowing the binary rules of a tree array, consider how to implement it in code.
int lowbit (x) { return x&-x;} void Update (int k,int x) { for (int i=k;i<=n;i+= lowbit (i)) { C[i]+ =x ;
0001, 0010, i.e. 0001 + 0001 = 0010;
0010, 0100, i.e. 0010 + 0010 = 0100;
0101, 0110, i.e. 0101 + 0001 = 0110;
0110, 1000, i.e. 0110 + 0010 = 1000;
The Lowbit function is to find the minimum number of carry, X&-x can understand:-X for the complement, for example, the original code & complement is equal to the minimum number of digits.
The update process is a for loop that updates the relevant elements in all C arrays, starting with the updated K.
int getsum (int x) { int ans=0; for (int i=x;i;i-=lowbit (i)) // I to be greater than 0 ans+=c[i]; return ans;}
1111, 1110, i.e. 1111- 0001 = 1110;
1110, 1100, i.e. 1110- 0010 = 1100;
1100, 1000, i.e. 1100- 0100 = 1000;
0000------ --0000;
By the same token, you can see that the sum is the next value to be added by subtracting the minimum number of digits .
Tree-like array-magical binary