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.
- First, the ANS is initialized to 0, and I is counted as K.
- Add the value of ans to bit[p]
- Subtract the value of I from Lowbit (i)
- 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)