线段树区间修改,区间查询的用结构体代码模板
时间: 2023-03-30 12:01:35 浏览: 108
以下是线段树区间修改,区间查询的用结构体代码模板:
```
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN = 100010;
struct Node {
int l, r;
int sum;
} tr[MAXN << 2];
int n, m;
int w[MAXN];
void pushup(int u) {
tr[u].sum = tr[u << 1].sum + tr[u << 1 | 1].sum;
}
void build(int u, int l, int r) {
if (l == r) tr[u] = {l, r, w[l]};
else {
tr[u] = {l, r};
int mid = l + r >> 1;
build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r);
pushup(u);
}
}
void modify(int u, int x, int c) {
if (tr[u].l == x && tr[u].r == x) tr[u].sum += c;
else {
int mid = tr[u].l + tr[u].r >> 1;
if (x <= mid) modify(u << 1, x, c);
else modify(u << 1 | 1, x, c);
pushup(u);
}
}
int query(int u, int l, int r) {
if (tr[u].l >= l && tr[u].r <= r) return tr[u].sum;
else {
int mid = tr[u].l + tr[u].r >> 1;
int res = ;
if (l <= mid) res += query(u << 1, l, r);
if (r > mid) res += query(u << 1 | 1, l, r);
return res;
}
}
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) scanf("%d", &w[i]);
build(1, 1, n);
while (m--) {
int k, x, y;
scanf("%d%d%d", &k, &x, &y);
if (k == 1) modify(1, x, y);
else printf("%d\n", query(1, x, y));
}
return ;
}
```
以上是回答你的问题,希望对你有所帮助。
阅读全文