Algorithm description
can query and modify a given sequence
Query: Mainly used to query the data between any two bits and
Modify: Modify a single data value
Time Complexity: Log (N)
Algorithmic thinking
1. Construction of arrays
Define Array C A
C1 = A1
C2 = A1 + A2
C3 = A3
C4 = A1 + A2 + A3 + A4
C5 = A5
C6 = A5 + A6
C7 = A7
C8 = A1 + A2 + A3 + A4 + A5 + A6 + A7 + A8
...
It is not difficult to see, in fact, the implementation of a data of the respective jurisdiction, CN, the jurisdiction of the number of n into a binary number, the end of a continuous number of 0; it can also be understood, so that 2^k <=n; The maximum value of K is the number of jurisdictions
Here is a method for finding 2^k, which will be used later
int lowbit(int x){ return//运用位运算及机器补码}
Call Lowbit (n) to derive the number of CN jurisdictions
And the CN jurisdiction is: N-lowbit (n) +1 to n
void make_tree(int n){ for(int i=1;i<=n;i++) { for(int j=i-lowbit(i)+1;j<=i;j++) { c[i]+=a[j]; } }}
2. Summation
Make sum=0;
Traverse, each time the binary number of n is the last one 1 to 0, then sum + = C[n],n=n-lowbit (n), until n<=0;
The sum value is the sum of the sequence 1 ~ n
int make_sum(int n){ int sum=0; while(n>0) { sum+=c[n]; n-=lowbit(n); } return sum;}
3. Modify individual data
Make changes to each CN containing AI
void modify(int n,int i,int num){ while(i<=n) { c[i]+=num-a[i]; i+=lowbit(i); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Tree-like array learning (one-dimensional)