Learning Reference:
79165701
52770728
The tree-like array in the winter vacation training in fact, but there was a board, not very deep to learn to understand, and now come back to understand this very useful data structure.
The role of a tree-like array
A tree-like array is a good data structure for dealing with dynamic updates, dynamic statistical interval problems, and querying and modifying data structures with the complexity of O (Logn).
The tree-like array is mainly for single-point modification and interval query operation.
Lowbit ()
For example, to find out 2^p (where the binary representation of p:x, right-to-left number the first 1 of the position), such as 6 of the binary representation is 110, the left number 0th is 0, the first is 1, then p=1, so lowbit (6) = 2^1 = 2.
The main function of Lowbit is to find 1 of the lowest one in a number binary, and the commonly used lowbit function skillfully uses the characteristic of negative integer complement. The code is as follows
int lowbit (int x) { return x& (-x);}
Several operations: Add the number of I to X, modify the value of the number I, delete the number of I, statistics I to the number of J and
The principle of the tree array is to add an auxiliary sequence C array, which makes C[i]=a[i-2k+1]+a[i-2k+2]+...+a[i], where K is the number of the end 0 in the binary form of I.
1#include <bits/stdc++.h>2 #defineFi first3 #defineSe Second4 #definePB Push_back5 #defineFio Ios::sync_with_stdio (false); Cin.tie (0);6 #definePII pair<int,int>7 #defineVI vector<int>8 #defineVC Vector<char>9 #defineMii map<int,int>Ten #defineSi (a) scanf ("%d", &a) One #defineSS (a) scanf ("%s", &a) A #defineSL (a) scanf ("%i64d", &a); - #defineSLF (a) scanf ("%lf", &a); - #defineCLEAR (A, B) memset (A,b,sizeof (a)) the #definePi ACOs (-1) - -typedefDoubledb; -typedefLong Longll; +typedef unsignedLong Longull; - + Const intinf=0x3f3f3f3f; A Const intn=2e5+5; at using namespacestd; - intS[n]; - intN; - intLowbit (intx) - { - returnx& (-x); in } - to voidAddintIintj) + { - while(i<=N) the { *s[i]+=J; $i+=lowbit (i);Panax Notoginseng } - } the + A intQuery (intk) the { + intRe=0; - while(k>0) $ { $re+=S[k]; -k-=Lowbit (k); - } the returnre; - }Wuyi the - voidSubintIintj) Wu { - while(i<=N) About { $s[i]-=J; -i+=lowbit (i); - } - } A + the intMain () - { $ the}
Tree-like array review learning