Tree arrays - array operations ( nkoj1321 )
topic analysis
tree array bare question
tree array
lowbit:i & -i
Since -i is expressed in complement, that is, each bit is inverted +1, so it i & -i
represents the value represented by the last 1 of i, such as lowbit(8)=8, lowbit(12)=4
operate
- new
void build();
Record a prefix sum array ps, and then according to the nature of the tree array, s[i]=ps[i] - ps[i - (i & -i)]
, s[i] can be understood as the sum within the jurisdiction of i
- Revise
void add(int pos, int delta);
i starts from pos and increases lowbit(i) each time, so that delta is added to all s[i] containing pos
- sum
int sum(int pos);
i starts from pos and subtracts lowbit(i) each time, so that s[i] is the sum of each segment, and adding them all together is the prefix sum
code
//
// Created by rv on 2018/4/22.
//
#include <cstring>
#include <cstdio>
const int N = 100000 + 5;
// 注意下标一定不能从0开始
int A[N], ps[N];
int s[N];
void build() {
for (int i = 1; i <= N; i++) {
ps[i] = ps[i - 1] + A[i];
s[i] = ps[i] - ps[i - (i & -i)];
}
}
// 第pos个数加delta
void add(int pos, int delta) {
for (int i = pos; i <= N; i += i & -i) {
s[i] += delta;
}
}
// 前pos个数的和
int sum(int pos) {
int res = 0;
for (int i = pos; i >= 1; i -= i & -i) {
res += s[i];
}
// printf("sum: %d %d\n", pos, res);
return res;
}
// [l,r]区间和
int ask(int l, int r) {
// printf("ask: %d %d\n", l, r);
return sum(r) - sum(l - 1);
}
int main() {
// freopen("data.in", "r", stdin);
int n, m, x, y, tmp;
char str[4];
char SUM[] = "SUM";
char ADD[] = "ADD";
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &A[i]);
// scanf("%d", &tmp);
// add(i, tmp);
}
// for (int i = 1; i <= n; i++) {
// printf("%d ", A[i]);
// }
// printf("\n");
build();
// for (int i = 1; i <= n; i++) {
// printf("%d ", ps[i]);
// }
// printf("\n");
// for (int i = 1; i <= n; i++) {
// printf("%d ", s[i]);
// }
// printf("\n");
scanf("%d", &m);
while (m--) {
scanf("%s%d%d", str, &x, &y);
// printf("str: %s\n", str);
if (strcmp(str, SUM) == 0) {
// printf("sum: ");
printf("%d\n", ask(x, y));
} else if (strcmp(str, ADD) == 0) {
// printf("add: ");
add(x, y);
} else {
printf("bad scanf");
}
}
return 0;
}
pit
The return of strcmp is equal to 0, and it was reversed at the beginning and adjusted for a while...