Description
You have N integers, A1, A2, ... , AN. You need to deal with two kinds of operations. One type of operation is to add some given number to each number in a given interval. The other is to ask for the sum of numbers in a given interval.
Input
The first line contains two numbers N and Q. 1 ≤ N,Q ≤ 100000.
The second line contains N numbers, the initial values of A1, A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of Aa, Aa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of Aa, Aa+1, ... , Ab.
Output
You need to answer all Q commands in order. One answer in a line.
Sample Input
10 5 1 2 3 4 5 6 7 8 9 10 Q 4 4 Q 1 10 Q 2 4 C 3 6 3 Q 2 4
Sample Output
4 55 915
solution:
LAZY模板题~
#include<cstdio> #include<algorithm> using namespace std; const int maxn = 1e5+200; #define ls t<<1 #define rs (t<<1)|1 struct node{ long long val,lazy; int l, r; }tree[maxn * 4]; void pushup(int t) { tree[t].val = tree[ls].val + tree[rs].val; } void build(int l, int r, int t) { tree[t].l = l; tree[t].r = r; tree[t].lazy = 0; if (l == r) { scanf("%lld", &tree[t].val); return; } build(l, (l + r) / 2, ls); build((l + r) / 2 + 1, r, rs); pushup(t); } void pushdown(int t) { if (tree[t].lazy) { tree[ls].lazy+= tree[t].lazy; tree[ls].val+= (tree[ls].r - tree[ls].l + 1)*tree[t].lazy; tree[rs].lazy+= tree[t].lazy; tree[rs].val+= (tree[rs].r - tree[rs].l + 1)*tree[t].lazy; tree[t].lazy = 0; } } void update(int l,int r,int t,long long k) { if (tree[t].l >= l&&tree[t].r <= r) { tree[t].lazy += k; tree[t].val+= (tree[t].r - tree[t].l + 1)*k; return; } pushdown(t); int mid = (tree[t].l + tree[t].r) / 2; if (l <= mid)update(l, r, ls, k); if (r > mid)update(l, r, rs, k); pushup(t); } long long Query(int l, int r, int t) { long long sum = 0; if (tree[t].l >= l&&tree[t].r <= r) return tree[t].val; pushdown(t); int mid = (tree[t].l + tree[t].r) / 2; if (l <= mid)sum+=Query(l, r, ls); if (r > mid)sum+=Query(l, r, rs); return sum; } int main() { int t, n, m, nn, x, y; long long z; char op[10]; while (~scanf("%d%d", &n, &m)) { build(1, n, 1); while (m--) { scanf("%s%d%d", op, &x, &y); if (op[0] == 'Q')printf("%lld\n", Query(x, y, 1)); else { scanf("%lld", &z); update(x, y, 1, z); } } } }