写一段c++的线段树代码
时间: 2023-10-18 21:16:43 浏览: 79
线段树详解(C++版).pdf
下面是一个简单的线段树代码,用于查询区间最小值和区间和。
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXN 1000000
struct node {
int l, r;
int minv, sum;
} tree[MAXN << 2];
int a[MAXN];
void build(int p, int l, int r) {
tree[p].l = l;
tree[p].r = r;
if (l == r) {
tree[p].minv = a[l];
tree[p].sum = a[l];
return;
}
int m = (l + r) >> 1;
build(p << 1, l, m);
build(p << 1 | 1, m + 1, r);
tree[p].minv = tree[p << 1].minv < tree[p << 1 | 1].minv ? tree[p << 1].minv : tree[p << 1 | 1].minv;
tree[p].sum = tree[p << 1].sum + tree[p << 1 | 1].sum;
}
void update(int p, int x, int v) {
if (tree[p].l == x && tree[p].r == x) {
tree[p].minv = v;
tree[p].sum = v;
return;
}
int m = (tree[p].l + tree[p].r) >> 1;
if (x <= m) update(p << 1, x, v);
else update(p << 1 | 1, x, v);
tree[p].minv = tree[p << 1].minv < tree[p << 1 | 1].minv ? tree[p << 1].minv : tree[p << 1 | 1].minv;
tree[p].sum = tree[p << 1].sum + tree[p << 1 | 1].sum;
}
int query_min(int p, int l, int r) {
if (tree[p].l == l && tree[p].r == r) {
return tree[p].minv;
}
int m = (tree[p].l + tree[p].r) >> 1;
if (r <= m) return query_min(p << 1, l, r);
else if (l > m) return query_min(p << 1 | 1, l, r);
else return query_min(p << 1, l, m) < query_min(p << 1 | 1, m + 1, r) ? query_min(p << 1, l, m) : query_min(p << 1 | 1, m + 1, r);
}
int query_sum(int p, int l, int r) {
if (tree[p].l == l && tree[p].r == r) {
return tree[p].sum;
}
int m = (tree[p].l + tree[p].r) >> 1;
if (r <= m) return query_sum(p << 1, l, r);
else if (l > m) return query_sum(p << 1 | 1, l, r);
else return query_sum(p << 1, l, m) + query_sum(p << 1 | 1, m + 1, r);
}
int main() {
int n, m;
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, x, y);
} else if (op == 2) {
printf("%d\n", query_min(1, x, y));
} else if (op == 3) {
printf("%d\n", query_sum(1, x, y));
}
}
return 0;
}
```
阅读全文