【模板】樹狀數組
阿新 • • 發佈:2018-08-06
clu spa sca += urn return names 樹狀數組 printf
題意簡述
已知一個數列,你需要進行下面兩種操作:
1.將某一個數加上x
2.求出某區間每一個數的和
代碼
#include <cstdio> using namespace std; int n, m; int a[500001]; inline int lb(int x) { return x & (-x); } void add(int x, int k) { for (int i = x; i <= n; i += lb(i)) a[i] += k; } int sum(int x) { int ans = 0; for (int i = x; i; i -= lb(i)) ans += a[i]; return ans; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; ++i) { int x; scanf("%d", &x); add(i, x); } for (int i = 1; i <= m; ++i) { int op, x, y; scanf("%d%d%d", &op, &x, &y); if (op == 1) add(x, y); else printf("%d\n", sum(y) - sum(x - 1)); } }
【模板】樹狀數組