先复习一遍线段树。。。。
代码:
#include <iostream> #include <cstdio> #define maxn 100015 #define lid (id<<1) #define rid ((id<<1)|1) #define LL long long long long a[maxn]; struct segtree { int l, r; long long sum, lazy; }tr[maxn*4]; void push_down(int id) { if (tr[id].lazy != 0) { tr[lid].sum += (tr[lid].r - tr[lid].l + 1)*tr[id].lazy; tr[lid].lazy += tr[id].lazy; tr[rid].sum += (tr[rid].r - tr[rid].l + 1)*tr[id].lazy; tr[rid].lazy += tr[id].lazy; tr[id].lazy = 0; } } void bulid(int id, int l, int r) { tr[id].l = l; tr[id].r = r; if (l == r) { tr[id].sum = a[l-1]; return; } int mid = (l + r) >> 1; bulid(lid, l, mid); bulid(rid, mid + 1, r); tr[id].sum = tr[lid].sum + tr[rid].sum; } void update(int id, int l, int r,long long v) { if (l == tr[id].l&&tr[id].r == r) { tr[id].sum += (tr[id].r - tr[id].l + 1)*v; tr[id].lazy += v; return; } push_down(id); int mid = (tr[id].l + tr[id].r) >> 1; if (r <= mid) update(lid, l, r, v); else if (l > mid) update(rid, l, r, v); else { update(lid, l, mid, v); update(rid, mid + 1, r, v); } tr[id].sum = tr[lid].sum + tr[rid].sum; } long long query(int id, int l, int r) { if (l == tr[id].l&&r == tr[id].r) return tr[id].sum; push_down(id); int mid = (tr[id].l + tr[id].r) >> 1; if (r <= mid) return query(lid, l, r); else if (l > mid) return query(rid, l, r); else return query(lid, l, mid) + query(rid, mid + 1, r); } int main() { int n, m, l, r; long long v; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%lld", &a[i]); bulid(1, 1, n); scanf("%d", &m); while (m--) { scanf("%d %d %lld", &l, &r, &v); update(1, l, r, v); printf("%lld", query(1, l, r)); if (m!=0) printf("\n"); } return 0; }