#include <bits/stdc++.h> using namespace std; const int N = 1e5 + 5; int n, m; int w[N]; struct node { int l, r; LL sum, add; }tr[N * 4]; void pushup(int u) { tr[u].sum = tr[u << 1].sum + tr[u << 1 | 1].sum; } void pushdown(int u) { auto &root = tr[u], &left = tr[u << 1], &right = tr[u << 1 | 1]; if (root.add) { left.add += root.add, left.sum += (LL)(left.r - left.l + 1) * root.add; right.add += root.add, right.sum += (LL)(right.r - right.l + 1) * root.add; root.add = 0; } } void build(int u, int l, int r) { if (l == r) tr[u] = {l, r, w[l], 0}; else { tr[u] = {l, r};//不要忘 int mid = l + r >> 1; build(u << 1, l, mid), build(u << 1 | 1, mid + 1, r); pushup(u);//pushup } } void modify(int u, int l, int r, int x) { if (tr[u].l >= l && tr[u].r <= r) { tr[u].sum += (LL)(tr[u].r - tr[u].l + 1) * x; tr[u].add += x; } else { pushdown(u);//modify之间要pushdown int mid = tr[u].l + tr[u].r >> 1; if (l <= mid) modify(u << 1, l, r, x); if (r > mid) modify(u << 1 | 1, l, r, x); pushup(u);//注意pushup } } LL query(int u, int l, int r) { if (tr[u].l >= l && tr[u].r <= r) return tr[u].sum; pushdown(u); int mid = tr[u].l + tr[u].r >> 1; LL ans = 0; if (l <= mid) ans = query(u << 1, l, r); if (r > mid) ans += query(u << 1 | 1, l, r); return ans; } int main() { cin >> n >> m; for (int i = 1; i <= n; i ++) cin >> w[i]; build(1, 1, n); while (m --) { char op; cin >> op; int l, r, x; cin >> l >> r; if (op == 'Q') cout << query(1, l, r) << endl; else { cin >> x; modify(1, l, r, x); } } return 0; }
标签:int,线段,tr,ans,区间,sum,模板,op From: https://www.cnblogs.com/Leocsse/p/16789621.html