http://acm.uestc.edu.cn/#/problem/show/1057
题意:给你n个数,q次操作,每次在l,r上加上x并输出此区间的sum
题解:线段树模板,
#define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<stdio.h> using namespace std; const int maxn = 1e5 + 5; int a[maxn], n, q, l, r, val; typedef long long ll; struct node { int l, r; long long sum, lazy; void update(long long x) { sum += (ll)1*(r - l + 1)*x; lazy += x; } }tree[maxn*4]; void push_up(int x) { tree[x].sum = tree[x << 1].sum + tree[x << 1 | 1].sum; } void push_down(int x) { int lazyval = tree[x].lazy; if (lazyval) { tree[x << 1].update(lazyval); tree[x << 1 | 1].update(lazyval); tree[x].lazy = 0; } } void build(int x, int l, int r) { tree[x].l = l; tree[x].r = r; tree[x].sum = tree[x].lazy = 0; if (l == r) { tree[x].sum = a[l]; } else { int mid = l + r >> 1; build(x << 1, l, mid); build(x << 1 | 1, mid + 1, r); push_up(x); } } void update(int x, int l, int r, long long val) { int L = tree[x].l, R = tree[x].r; if (l == L&&r == R) { tree[x].update(val); } else { push_down(x); int mid = L + R >> 1; if (mid >= l)update(x << 1, l, r, val); if (r > mid)update(x << 1 | 1, l, r, val); push_up(x); } } long long query(int x,int l,int r) { int L = tree[x].l, R = tree[x].r; if (l == L&&r == R) { return tree[x].sum; } else { push_down(x); long long ans = 0; int mid = L + R >> 1; if (mid >= l)ans+=query(x << 1, l, r); if (r > mid)ans += query(x << 1 | 1, l, r); push_up(x); return ans; } } int main() { cin >> n; for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); } build(1, 1, n); cin >> q; for (int i = 1; i <=q; i++) { scanf("%d%d%d", &l, &r, &val); update(1,l,r,val); printf("%lld ",query(1, l, r)); } }