1. Overview
A tree-like array (binary indexed) is a novel array structure that can efficiently obtain the number of consecutive n in an array. In a nutshell, a tree array is often used to solve the problem that elements in the array {A} can be constantly modified and how to quickly get the sum of several consecutive numbers.
2, tree-like array of basic operations
The complexity of the element modification of the traditional array (n elements) and the summation of successive elements is O (1) and O (n), respectively. The tree array transforms the linear structure into pseudo tree structure (the linear structure can only scan the elements one by one, while the tree structure is capable of jumping scanning), which makes the modification and summation complexity O (LGN), and greatly improves the overall efficiency.
Given a sequence (series) A, we set an array C to satisfy
C[i] = a[i–2^k+ 1] + ... + a[i]
where k is the number of I at the end of the binary 0, I start from 1.
Then we call c a tree-like array.
The question below is, given I, how do I find 2^k?
The answer is simple:2^k=i& (i^ (i-1)), i.e. i& (-i)
The following explains:
Take I=6 as an example (note: a_x indicates that the number a is an X-form representation):
(i) _10 = (0110) _2
(i-1) _10= (0101) _2
I xor (i-1) = (0011) _2
I and (I xor (i-1)) = (0010) _2
2^k = 2
C[6] = c[6-2+1]+...+a[6]=a[5]+a[6]
The exact meaning of the array C is shown in the following illustration:
When we modify the value of a[i], we can go back to the root node and adjust all the c[on this path from C[i], and the complexity of the operation is at worst the height of the tree, O (logn). In addition, for the first n items of the sequence, we simply find all the largest subtrees before N, and add up the C of the root node. It's not hard to find that the number of these subtrees is the number of n at binary 1, or the number of items that expand N to 2 power and time, so the complexity of the sum operation is also O (Logn).
The tree array can quickly find the sum of any interval: A[i] + a[i+1] + ... + a[j], set sum (k) = A[1]+a[2]+...+a[k], then a[i] + a[i+1] = SUM (j) a[j (-sum).
The following gives the C-language implementation of the tree array: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 The 9 40 41 42 43 44 45 46 47 48 49//Seek 2^k int lowbit (int t) {return T & (t ^ (t-1)); //ask for n and int sum (int end) {int sum = 0; while (End > 0)