POJ 3468 A Simple Problem with Integers 线段树区间修改
区间增加
区间查询和
struct Tree { int l, r; ll sum; }; Tree node[maxn * 4]; ll a[maxn]; ll lazy[maxn * 4]; void Pushdown(int rt, int m) { if (lazy[rt]) { lazy[rt << 1] += lazy[rt]; lazy[rt << 1 | 1] += lazy[rt]; node[rt << 1].sum += lazy[rt] * (m - (m >> 1)); node[rt << 1 | 1].sum += lazy[rt] * (m >> 1); lazy[rt] = 0; } } void Pushup(int i) { node[i].sum = node[i << 1].sum + node[i << 1 | 1].sum; } void Build(int i, int l, int r) { lazy[i] = 0; node[i].l = l; node[i].r = r; if (l == r) { node[i].sum = a[l]; return; } int mid = l + r >> 1; Build(i << 1, l, mid); Build(i << 1 | 1, mid + 1, r); Pushup(i); } ll getsum(int i, int l, int r) { if (node[i].l == l && node[i].r == r) return node[i].sum; int mid = node[i].l + node[i].r >> 1; Pushdown(i, node[i].r - node[i].l + 1); if (r <= mid) return getsum(i << 1, l, r); else if (l > mid) return getsum(i << 1 | 1, l, r); else return getsum(i << 1, l, mid) + getsum(i << 1 | 1, mid + 1, r); } void update(int i, int l, int r, ll v) { if (node[i].r == r && node[i].l == l) { lazy[i] += v; node[i].sum += (ll)v * (r - l + 1); return; } if (node[i].l == node[i].r) return; int mid = node[i].l + node[i].r >> 1; Pushdown(i, node[i].r - node[i].l + 1); if (r <= mid) update(i << 1, l, r, v); else if (l > mid) update(i << 1 | 1, l, r, v); else { update(i << 1, l, mid, v); update(i << 1 | 1, mid + 1, r, v); } Pushup(i); } int main() { int n, q; int l, r; char op[3]; n = readint(), q = readint(); for (int i = 1; i <= n; i++) a[i] = readll(); Build(1, 1, n); while (q--) { scanf("%s", op); l = readint(), r = readint(); if (strcmp(op, "C") == 0) { ll val = readll(); update(1, l, r, val); } else { Put(getsum(1, l, r)); puts(""); } } }