用c++写出线段树的模板代码
时间: 2023-04-03 11:00:22 浏览: 116
好的,以下是线段树的模板代码:
```c
#include <stdio.h>
#define MAXN 100005
int n, m;
int a[MAXN];
int tree[MAXN << 2];
void build(int node, int left, int right) {
if (left == right) {
tree[node] = a[left];
return;
}
int mid = (left + right) >> 1;
build(node << 1, left, mid);
build(node << 1 | 1, mid + 1, right);
tree[node] = tree[node << 1] + tree[node << 1 | 1];
}
void update(int node, int left, int right, int pos, int val) {
if (left == right) {
tree[node] = val;
return;
}
int mid = (left + right) >> 1;
if (pos <= mid) update(node << 1, left, mid, pos, val);
else update(node << 1 | 1, mid + 1, right, pos, val);
tree[node] = tree[node << 1] + tree[node << 1 | 1];
}
int query(int node, int left, int right, int l, int r) {
if (left >= l && right <= r) return tree[node];
int mid = (left + right) >> 1, res = ;
if (l <= mid) res += query(node << 1, left, mid, l, r);
if (r > mid) res += query(node << 1 | 1, mid + 1, right, l, r);
return res;
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
build(1, 1, n);
while (m--) {
int op, x, y;
scanf("%d%d%d", &op, &x, &y);
if (op == 1) update(1, 1, n, x, y);
else printf("%d\n", query(1, 1, n, x, y));
}
return ;
}
```
希望能够帮到你!
阅读全文