#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn = 1e6 + 10;
const int mod = 1e9 + 7;
const int INF = 1e9 + 10;
const int N = 1e6;
int n, m;
int f[N],a[N];//f[i]下表为i的节点对应区间和
inline void buildtree(int k, int l, int r){
if(l == r){
f[k] = a[l];
return;
}
int m = (l + r) >> 1;
buildtree(k + k, l, m);
buildtree(k + k + 1, m + 1, r);
f[k] = f[k + k] + f[k + k + 1];
}
inline void add(int k, int l, int r, int x, int y){
f[k] += y;
if(l == r)
return;
int m = (l + r) >> 1;
if(x <= m){
add(k + k, l, m, x, y);
}
else
add(k + k + 1, m + 1, r, x, y);
}
int calc(int k, int l, int r,int s,int t){
if(l == s && r == t)
return f[k];
int m = (l + r) >> 1;
if(t <= m)
return calc(k + k, l, m, s, t);
else
if(s > m)
return calc(k + k + 1, m + 1,r, s, t);
else
return calc(k + k, l, m, s, m) + calc(k + k + 1, m + 1, r, m + 1, t);
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n >> m;
for(int i = 1;i <= n;i ++)
cin >> a[i];
buildtree(1, 1, n);
for(int i = 1;i <= m; i++){
int t, x, y;
cin >> t >> x >> y;
if(t == 1)
add(1, 1, n, x, y);
else
cout << calc(1, 1, n, x, y) << endl;
}
return 0;
}
P3372 【模板】线段树 1
最新推荐文章于 2025-12-12 16:37:00 发布
这篇博客介绍了线段树这一数据结构的基础知识,并通过C++代码展示了如何构建和操作线段树,包括区间更新和区间查询。线段树在解决区间动态维护和查询问题上表现出高效性。
481

被折叠的 条评论
为什么被折叠?



