写一个线段树,用C++
时间: 2023-12-27 15:54:01 浏览: 80
以下是一个简单的线段树实现,包含区间修改和查询最大值的功能。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXN 100005
int n, m;
int a[MAXN];
int tree[MAXN << 2];
void build(int k, int l, int r) {
if (l == r) {
tree[k] = a[l];
return;
}
int m = (l + r) >> 1;
build(k << 1, l, m);
build(k << 1 | 1, m + 1, r);
tree[k] = tree[k << 1] > tree[k << 1 | 1] ? tree[k << 1] : tree[k << 1 | 1];
}
void update(int k, int l, int r, int x, int v) {
if (l == r) {
tree[k] = v;
return;
}
int m = (l + r) >> 1;
if (x <= m) {
update(k << 1, l, m, x, v);
} else {
update(k << 1 | 1, m + 1, r, x, v);
}
tree[k] = tree[k << 1] > tree[k << 1 | 1] ? tree[k << 1] : tree[k << 1 | 1];
}
int query(int k, int l, int r, int x, int y) {
if (x <= l && r <= y) {
return tree[k];
}
int m = (l + r) >> 1, ret = 0;
if (x <= m) {
ret = query(k << 1, l, m, x, y);
}
if (y > m) {
int t = query(k << 1 | 1, m + 1, r, x, y);
if (t > ret) {
ret = t;
}
}
return ret;
}
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 0;
}
```
阅读全文