Tree-like array
The modification and summation of the tree array are O (Logn), which is very efficient.
The tree-like array--lowbit (x) For example 212 binary is where 10101,1 is located 0,2,4, which can be decomposed into 2^4 + 2 ^ 2 + ^ 0. Further [1,x] can be decomposed into an O (LOGX) Small interval:
1. Small interval of length 2^4 [1,2^4]
2. Small interval of length 2^2 [2^4 + 1,2^4+2^2]
3. Small interval of length 2^0 [2^4+2^2+1,2^4+2^2+2^0]
Tree-like array
C[1] = a[1];
C[2] = a[1] + a[2];
C[3] = a[3];
C[4] = a[1] + a[2]+a[3] + a[4];
C[5] = a[5];
C[6] = a[6] + a[5];
C[7] = a[7];
C[8]=A[1] + a[2]+a[3] + a[4]+a[5] + a[6]+a[7] + a[8]
A tree-like array satisfies the following properties:
1. Each internal node C[x] holds all the leaf nodes of the subtree with which it is rooted.
2. The number of child nodes of each internal node c[x] is equal to the size of Lowbit (x).
3. The parent node of each internal node C[x] is C[x + lowbit (x) except for the root tree)
4. The depth of the tree is O (logn).
I. Seeking Lowbit (n)
Lowbit (n) is the value of the non-negative integer n in the binary representation of the lowest bit 1 and the 0 behind it.
{The complement expression ~n = -1-n} so lowbit (n) = n& (~n+1) = n& (-N).
1 int lowbit (n) 2 {3 return n& (-n); 4 }
Second, add an element to the operation
The ancestors of any one node were at most only Logn, and we updated each of their array C values. The following code performs a single point increment operation in O (Logn) time.
1 void Update (int x,int y)2{3for 1 ; I <= n;x + = x & (-x))4 {5 c[x] = c[x] + y; 6 }7 }
Third, the query prefix and
As written at the beginning of this article, divided into O (logn) arrays, each array of intervals and all have been saved in the array C, the following code in O (logn) time query prefix and.
1 intSumintx)2 {3 intAns =0;4 while(X >0)5 {6Ans = ans +C[x];7x = x-(X & (-x));8 returnans;9 }Ten}
Iv. Statistics A[x] ... The value of A[y].
Call the sum of the above operation: Sum (y)-sum (x-1)
V. Extensions (Multidimensional tree arrays)
Complexity into O (LOGN) ^m
There is a n*m two-dimensional array, the tree array is C, then the single-point modification operation is:
1 intUpdateintXintYintZ//Add (x, y) value to Z2 {3 intI=x;4 while(I <=N)5 {6 intj =y;7 while(J <=m)8 {9C[I][J] + =Z;TenJ + =Lowbit (j); One } Ai + =lowbit (i); - } -}
1 intSumintXinty)2 {3 intres =0, i =x;4 while(I >0)5 {6 intj =y;7 while(J >0)8 {9res = res +C[i][j];TenJ-=Lowbit (j); One } AI-=lowbit (i); - } - returnRes; the}
VI. matters of caution
The subscript of a tree array cannot be 0, otherwise lowbit (0) = 0 will fall into the dead loop.
Tree-like array