Tree-like array

Source: Internet
Author: User
Tags readline

First, the basic concept

A tree-like array (Binary Indexed tree (BIT), Fenwick tree) is a data structure that queries and modifies the complexity of both log (n). It is a very useful data structure that is used to quickly query the sum of all the elements between any two bits. It is by using node I, records the array subscript in [I–2^k + 1, i] this interval of all the number of information (where k is the binary representation of I in the number of the end 0, set lowbit (i) = 2^k), to achieve in O (log n) time to find and update the array of data.

Example one:

A school has n classes, at first there are no students in each class, the school admissions office encountered a difficult problem, they must always know the total number of the top N classes (task one), and at any time will increase the number of people to a certain class (task two). We can easily think of a simple algorithm, open an array of length n to record the number of each class, so the time to complete task two of the complexity is O (1), but the completion of task one time complexity is O (n) so slow.

We can also use A[i] to record the total number of previous I classes, so that the time complexity of completing task one is O (1) But the time complexity of completing task two is O (n). Both of these methods are slow in the case of N very large. So we have to introduce new data structures--arrays of numbers.

We also use example one as an example to define array a, where a[i] represents the number of Class I classes. Define an array c[i] where C[i]=a[i-2^k+1]+......+a[i] (k is I in binary form the number of end 0). can be derived from the definition of C array

C[1]=A[1]
C[2]=A[1]+A[2]=C[1]+A[2]
C[3]=A[3]
C[4]=A[1]+A[2]+A[3]+A[4]=C[2]+C[3]+A[4]
C[5]=A[5]
C[6]=A[5]+A[6]=C[5]+A[6]
C[7]=A[7]
C[8]=A[1]+A[2]+A[3]+A[4]+A[5]+A[6]+A[7]+A[8]=C[4]+C[6]+C[7]+A[8]

..................

Visually represent such as:

Second, the principle analysis

  1. Array generation 

Set the node number to x, then this node is governed by 2^k (where K is the number of x binary end 0, that is, 2^k represents the number of binary last 1 for x) elements. Because the last element of this interval must be a[x], it is obvious: c[n] = a[n–2^k + 1] + ... + a[n], the value of this 2^k has a quick way to define a function as follows:

Using the machine complement feature:

int lowbit (int x)

{
Return x& (-X);
}

Example: Calculation c[6]

A binary representation of 6 is 0110

-6 binary representation is 1010 (6 complement)

The 0110
   & 1010
0010 = 2

Represents the c[6] node management interval is 2

C[6] = a[5] + a[6]

  2. Enquiry

When you want to query a sum (n) (for a[n), you can do this based on the following algorithm:

Step1: Make sum = 0, turn the second step;

Step2: If n <= 0, the algorithm ends, returns the sum value, otherwise sum = sum + c[n], to the third step;

Step3: Make n = N–lowbit (n), go to the second step.

It can be seen that this algorithm is to add this interval and all together, why is the efficiency is log (n)?

The following gives proof:

n = n–lowbit (n) This step is actually equivalent to subtracting the last 1 of the binary of N. The binary of n has a maximum of log (n) 1, so the query efficiency is log (n)

  3. Modifications

To modify a node, all its ancestors must be modified, worst of all to modify the first element, with a maximum of log (n) Ancestors

So the modification algorithm is as follows (to a node I plus x):

Step1: When i > N, the algorithm ends, otherwise turns the second step;

Step2:ci = Ci + x, i = i + lowbit (i) go to the first step.

(i = i +lowbit (i) This process is actually just a process of filling the end 1 with 0)

(indicates modifying the first element in the a array, the corresponding C array should be modified)

Third, the implementation of code construction
public int lowbit (int  index)     {         int temp = index   & (-index);          return temp;      }
/// <summary>///maintenance operations on a tree array after modifying an element value/// </summary>/// <param name= "index" >the index value of the element needs to be modified</param>/// <param name= "value" >Increment of element modification</param>     Public voidAddintIndexintvalue) {             while(Index < A.length)//A.length is the length of the original array{C[index]+=value; Index=lowbit (index); }        }
/// <summary> /// preprocessing a array of a (original array) to get a tree array of type C /// </summary>  Public void Pretreatment_atoc ()    {    for (int0; i < a.length; i++)        {        Add (i, a[i]);         }     }
/// <summary>///calculates the sum of elements starting from 0 to index values/// </summary>/// <param name= "index" >terminating element index value</param>/// <returns></returns> Public intSumintindex) {        ints =0;  while(Index >0) {s+=C[index]; Index-=lowbit (index); }        returns; }
/// <summary>///calculates the sum of the elements of the index value from start to end/// </summary>/// <param name= "Start" >starting element index value</param>/// <param name= "End" >end Element Index value</param>/// <returns></returns> Public intSum_starttoend (intStartintend) {            if(Start = =0)            {                returnsum (end); }            returnSUM (end)-SUM (Start-1); }
Iv. Analysis of examples

1. Title Description (Color the ball):
N balloons are lined up in a row, numbered from left to right in 1,2,3....N. Given 2 integers a B (a <= b <=n), Xiaoming paints each balloon a color from balloon A to balloon B in turn. But after many times, Xiaoming has forgotten that the first balloon has been painted several times, can you help him figure out how many times each balloon has been painted color?

2. Ideas

Let's say there are 8 balloons, after three staining.

With up-to-date, down-counting methods:

Each node in the tree array represents a segment interval, each update, according to its characteristics can be the starting point a after the range of a to find out, and then all the interval after a number of dyeing, and then all the interval B before the number of staining, thus modifying the tree array of [b] interval staining times.

3. Code implementation

Static voidMain (string[] args) {i=3;//number of staining processesConsole.WriteLine ("Please enter the total number of balloons:"); N= Int32.Parse (Console.ReadLine ());//example program, temporarily without exception handling, the sameBalloon =New int[n+1];  while(I >0) {i--; Console.WriteLine ("Please enter the starting position:"); A=Int32.Parse (Console.ReadLine ()); Console.WriteLine ("Please enter the end location:"); b=Int32.Parse (Console.ReadLine ()); Add (A,1);//start update from start positionAdd (b +1, -1);//cancels the update of the element after the terminating position} Console.WriteLine ("The number of times each balloon is coated is:");  for(intj =1; J <= N; J + +) {Console.Write (sum (j)+" ");//outputs the number of times each balloon is dyed} console.readkey (); }

4. Output

Tree-like array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.