树状数组基本模板
lowbit
1 inline int lowbit(int x)
2 {
3 return x & (-x);
4 }
单点修改
1 inline void update(int i, int x)
2 {
3 for (int pos = i; pos < MAXN; pos += lowbit(pos))
4 c[pos] += x;
5 }
单点查询
inline ll query(int x)
{
int ans = 0;
for (int pos = x; pos; pos -= lowbit(pos))
ans += c[pos];
return ans;
}
区间查询
1 inline ll query(int l, int r)
2 {
3 return query(r) - query(l - 1);
4 }
Luogu P3374
【模板】树状数组 1
代码
1 #include<bits/stdc++.h>
2 using namespace std;
3 using ll = long long;
4 #define N 500010
5 ll c[N];
6 ll a[N];
7 inline int lowbit(int x) { return x & (-x); }
8 inline void update(int i,int x)
9 {
10 for (int pos = i; pos<N;pos+=lowbit(pos))
11 c[pos] += x;
12 }
13 inline ll query(int x)
14 {
15 int ans = 0;
16 for (int pos = x; pos;pos-=lowbit(pos))
17 ans += c[pos];
18 return ans;
19 }
20 inline ll query(int l,int r)
21 {
22 return query(r) - query(l - 1);
23 }
24 int main()
25 {
26 ios::sync_with_stdio(false);
27 cin.tie(0);
28 int n, m;
29 cin >> n >> m;
30 for (int i = 1; i <= n;i++)
31 {
32 cin >> a[i];
33 update(i, a[i]);
34 }
35 for (int i = 1; i <= m;i++)
36 {
37 ll op, x, y;
38 cin >> op >> x >> y;
39 if(op==1)
40 update(x, y);
41 else
42 {
43 cout << query(x, y)<<"\n";
44 }
45 }
46 return 0;
47 }