树状数组模板
程序员文章站
2024-03-02 23:34:34
...
复习一下,以免忘记
// 树状数组维护的是一个前缀和
#include <bits/stdc++.h>
#define mem(a, b) memset(a, b, sizeof a)
#pragma warning (disable:6031)
#pragma warning (disable:4996)
using namespace std;
const int N = 310;
int tree[N];
int n;
int lowbit(int x) {
return x & -x;
}
void add(int x, int d) {
while (x <= n) {
tree[x] += d;
x += lowbit(x);
}
}
int query(int x){
int res = 0;
while (x) {
res += tree[x];
x -= lowbit(x);
}
return res;
}
int main()
{
mem(tree, 0);
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
add(i, i);
}
printf("%d\n", query(n));
return 0;
}