Tree-like array
Tree-like array:
is a novel design of the array structure, it can efficiently get the number of consecutive n in the array.
Linear structures can only scan elements one by one, while a tree-like structure allows for a jump scan.
Generally speaking:
A tree array is typically used to address the following issues:
The elements in the array {A} may be constantly modified, how can I get a number of consecutive numbers quickly?
In general, the tree-like array will have the following diagram:
The following figure is parsed to find out the pattern:
According to the figure:
C1 = A1
C2 = A2
C3 = A3
c4 = A1 + A2 + A3 + A4
C5 = A5
C6 = a5 + a6
C7 = A7
C8 = A1 + A2 + A3 + A4 + a5 + a6 + A7 + a8
C9 = A9
The analysis of the above-mentioned sets of formulas indicates:
When I is an odd number
CI = AI
When I is an even number
It depends on how many times I have a power of 2.
For Example:
A factor of 6 has a power of 2, equal to 2. So C6 = a5 + a6 (by 6 forward number two number of the and).
4 of the factor of oil 2 of two power, equal to 4. So c4 = A1 + A2 + A3 + A4 (by 4 forward number of four digits and).
First, there is the formula CN = A (n-a^k + 1) + ... + an (where k is n in the binary representation of the number of 0 from right to left).
So how do you ask for a^k?
The method is as follows:
1 int lowbit (int x)2{3 return x & (-x); 4 }
View Code
The return value of Lowbit () is the value of the 2^k.
After 2^k, the values of the array C are all out.
Next we require the and of all elements in the array.
Second, the algorithm of the array and the following:
① Order sum = 0, turn to step ②;
② Next, if n > 0, the sum = Sum + CN turns to step ③, otherwise, the terminating algorithm returns the value of sum;
③n = N-lowbit (n) (deletes the last 0 of the binary representation of N) and returns to the second step.
1 intSumintN)2 {3 intsum =0;4 while(N >0)5 {6sum+=C[n];7n = n-lowbit (n);8 }9 returnsum; Ten}
View Code
Third, when the elements in the array are changed, the tree array will play its advantage, (modified to give a node I plus x) algorithm as follows:
① when I < N, perform the next step; otherwise, the algorithm ends;
②ci = ci + x, i = i + lowbit (i) (at the end of the binary representation of I plus 0); return to step ①.
1 void Change (intint x)2{3while (i < = N)4 {5 c[i] = c[i] + x; 6 i = i + lowbit (i); 7 }8 }
View Code
Binary_indexed_tree (BIT)