Tree-like array (transported from Wikipedia)

Source: Internet
Author: User

tree-like array (Fenwick_tree), originally published by Peter M. Fenwick in 1994 with a New Data Structure for cumulative Frequency tables title in software practice and EX Perience. The original intention is to solve the computational problem of cumulative frequency (cumulative Frequency) in data compression, which is now used to calculate the prefix and the number of series efficiently. It can be obtained by the time and also by adding a constant to an item.

Basic Operation:

1) New;

2) Modification;

3) sum;

Lowbit Seeking method:

int lowbit (int  x) {    return x& (-x);}

NEW:

Defines an array BIT, which is used to maintain the prefix and, then:

Specific can be implemented in the following ways:

void build () {    for (int i=1; i<=max_n;i++)    {        bit[i] =a[ I];          for (int j=i-1; j>i-lowbit (i); j--)            Bit[i]+ =a[j];}    }
Modify:

Suppose you want to add a delta to the value now,

Then, you need to add the value of the covered interval to K.

This process can be written as a recursive, or a normal loop.

The number of calculations required is related to the number of bits of the data size n, i.e. the time complexity of this part is O (logn)

void edit (intint  delta) {    for (int j = i; J <= Max_n; J +=
   
     > Lowbit (j))        + =
     Delta;
   
sum:

Suppose we need to calculate the value.

    1. First, the ANS is initialized to 0, and I is counted as K.
    2. Add the value of ans to bit[p]
    3. Subtract the value of I from Lowbit (i)
    4. Repeat steps, or both, until the value of I changes to 0
int sum (int  k) {    int0;      for (int0; I -= Lowbit (i)        ) + = Bit[i]    ; return ans;}

Tree-like array (transported from Wikipedia)

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.