树状数组

2024-08-10

用于高效率地查询和维护前缀和,有区间修改和单点查询两个用途

#include <bits/stdc++.h>
#define io cin.tie(0), cout.tie(0), ios::sync_with_stdio(false)
#define LL long long
#define ULL unsigned long long
#define EPS 1e-8
#define INF 0x7fffffff
#define SUB -INF - 1
#define lowbit(x) ((x) & (-x))
using namespace std;
const int N = 1000;
int tree[N] = {0};
void update(int x, int d)
{
    while (x <= N)
    {
        tree[x] += d;
        x += lowbit(x);
    }
}
int sum(int x)
{
    int ans = 0;
    while (x > 0)
    {
        ans += tree[x];
        x -= lowbit(x);
    }
    return ans;
}
int a[11] = {0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
int main()
{
    io;
    for (int i = 1; i <= 10; i++)
        update(i, a[i]);
    cout << "old:[5,8]=" << sum(8) - sum(4) << endl;
    update(5, 100);
    cout << "new:[5,8]=" << sum(8) - sum(4);
    return 0;
}