The past few days have been learning the tree-like array, but still smattering.
Given an array, if you want to ask for all the sums in the sum, you will generally think of the accumulation, but when the array is large, the accumulation is too time-consuming, the complexity of the O (n), and the use of an additive method has a limitation, that is, when the array of one element, Still let you ask for an array of elements of the and, it seems troublesome, so we need to use a tree array, it to the time of the complexity of O (LGN), compared to much faster,. Here's a look at what a tree-like array is:
The tree-like array is mainly used in an accumulation of ideas, the following look at the tree array diagram, easy to understand:
According to the following:
C1=A1C2=A1+A2C3=A3C4=A1+A2+A3+A4C5=A5C6=A5+A6C7=A7C8=A1+A2+A3+A4+A5+A6+A7+A8C9=A9, wait.
The analysis of the above groups shows that when I is odd, ci=ai;
When I is an even number, I have to look at a factor of up to two of how many times the power, for example, 6 of the factor has a power of two, equal to 2:
So C6=a5+a6 (from six forward number of the sum of two numbers), 4 of the factor has two of the two powers, equal to four, so C4=a1+a2+a3+a4 (by the four forward number four number of sum);
(1) There is a formula Cn=a (n-a^k+1) +.....an (where k is a binary representation of n in the number of 0 from right to left)
Here's how to find a^k:
<pre name= "code" class= "HTML" ><pre name= "code" class= "HTML" >int low (int n) {return n& (-n);}
The return value of low () is the value of the 2^k.
After finding the 2^k, the value of the array C can be calculated. Next we require the and of all elements in the array.
(2) The algorithm for calculating the array is as follows:
(a) First of all, to enable sum=0 to carry out the next step;
(b) Judge, if n>0, SUN=SUM+CN, proceed to the next step, otherwise, terminate the algorithm and return the value of sum.
(c) N=n-low (n) (delete the last 0 of the binary representation of N) and return to the second step to continue execution.
Code implementation:
<pre name= "code" class= "HTML" >int sum (int n) {int sum=0;while (n>0) {sum=sum+c[n];n=n-low (n);} return sum;}
(3) When the elements in the array change, the tree array can play its advantage, the algorithm is as follows: (when an array is changed, it is given a node I plus x)
(a) When I<=n, perform the next step, otherwise, the algorithm is accepted;
(b) C[i]=c[i]+x;i=i+low (i) (at the end of the binary representation of I plus 0), return to the first step.
Code implementation:
<pre name= "code" class= "CSharp" >void Change (int. I,int x) {while (i<=n) {c[i]=c[i]+x;i=i+low (i);}}
Tree-like array