树状数组了解一下

YourFather 2023-01-15 19:56:44

#include #include using namespace std; int tree[200005], n, m; int lowbit(int x) { return x & -x; } void add(int index, int num) { while (index <= n) { tree[index] += num; index += lowbit(index); } } int sum(int index) { int ret = 0; while (index > 0) { ret += tree[index]; index -= lowbit(index); } return ret; } int main() { scanf("%d %d", &n, &m); for (int i = 1; i <= n; i++) { int tmp; scanf("%d", &tmp); add(i, tmp); } for (int i = 1; i <= m; i++) { int qd, zd; scanf("%d %d", &qd, &zd); printf("%d\n", sum(zd) - sum(qd - 1)); } return 0; }