用C++写一段线段树标准格式
时间: 2023-03-31 11:03:16 浏览: 122
线段树(C++).pptx
我可以为您提供一段标准格式的线段树代码,如下所示:
```
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 5;
int n, m;
int a[MAXN], sum[MAXN << 2], lazy[MAXN << 2];
void pushup(int rt) {
sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];
}
void pushdown(int rt, int ln, int rn) {
if (lazy[rt]) {
lazy[rt << 1] += lazy[rt];
lazy[rt << 1 | 1] += lazy[rt];
sum[rt << 1] += lazy[rt] * ln;
sum[rt << 1 | 1] += lazy[rt] * rn;
lazy[rt] = ;
}
}
void build(int l, int r, int rt) {
if (l == r) {
sum[rt] = a[l];
return;
}
int mid = (l + r) >> 1;
build(l, mid, rt << 1);
build(mid + 1, r, rt << 1 | 1);
pushup(rt);
}
void update(int L, int R, int C, int l, int r, int rt) {
if (L <= l && r <= R) {
sum[rt] += C * (r - l + 1);
lazy[rt] += C;
return;
}
int mid = (l + r) >> 1;
pushdown(rt, mid - l + 1, r - mid);
if (L <= mid) update(L, R, C, l, mid, rt << 1);
if (R > mid) update(L, R, C, mid + 1, r, rt << 1 | 1);
pushup(rt);
}
int query(int L, int R, int l, int r, int rt) {
if (L <= l && r <= R) {
return sum[rt];
}
int mid = (l + r) >> 1, ans = ;
pushdown(rt, mid - l + 1, r - mid);
if (L <= mid) ans += query(L, R, l, mid, rt << 1);
if (R > mid) ans += query(L, R, mid + 1, r, rt << 1 | 1);
return ans;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
build(1, n, 1);
while (m--) {
int op, x, y, k;
cin >> op;
if (op == 1) {
cin >> x >> y >> k;
update(x, y, k, 1, n, 1);
} else {
cin >> x >> y;
cout << query(x, y, 1, n, 1) << endl;
}
}
return ;
}
```
阅读全文