#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
#include <cctype>
#include <unordered_set>
#include <unordered_map>
#include <stack>
using namespace std;
int a[1010], c[1010];
int n = 1010;
int lowbit(int x) {
// x 的二进制表示中,最低位的 1 的位置。
return x & -x;
}
void add(int x, int k) {
while (x <= n) { // 不能越界
c[x] = c[x] + k;
x = x + lowbit(x);
}
}
int getsum(int x) { // a[1]..a[x]的和
int ans = 0;
while (x >= 1) {
ans = ans + c[x];
x = x - lowbit(x);
}
return ans;
}
// O(n)建树
void init() {
for (int i = 1; i <= n; ++i) {
c[i] += a[i];
int j = i + lowbit(i);
if (j <= n)
c[j] += c[i];
}
}
int main() {
int n = 5;
fill_n(a, n, 0);
fill_n(c, n, 0);
a[1] = 1;
a[2] = 2;
a[3] = 3;
a[4] = 4;
a[5] = 5;
init();
int v = getsum(5);
printf("%d\n", v);
}
模板:树状数组
最新推荐文章于 2024-06-28 15:02:50 发布