樹狀數組(Binary Indexed Trees)其代碼簡潔,第一次碰見就被驚豔到了。數組
網上講解也有不少,我就簡單總結一下。spa
樹狀數組有以下幾個基本操做。code
首先要了解lowbit運算,二進制分解下最小的2的次冪。blog
#define lowbit(x) (x&(-x))
1.查詢前綴和it
int ask(int x) { int res = 0; for (; x; x -= lowbit(x)) res += b[x]; return res; }
2.單點增長class
void add(int x, int v) { for (; x <= n; x += lowbit(x)) b[x] += v; }
void init(){//線性構造 for (int i = 1; i <= n; i++){ pre[i] = pre[i - 1] + a[i]; c[i] = pre[i] - pre[i - lowbit(i)]; } }