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 abc" means adding c to each of Aa,
Aa+1, ... , Ab. -10000 ≤ c ≤ 10000. "Q
ab" means querying the sum of Aa,
Aa+1, ... , Ab.
// #include<bits/stdc++.h> #include<stdio.h> // using namespace std; constint Max = 1e5+2; #define ll long long #define lson rt<<1, l, mid #define rson (rt<<1)+1, mid+1, r
structNode { int l,r; ll sum,add; /* data */ }tree[Max<<2];
int mid = (l+r)>>1; build(lson); build(rson); push_up(rt); }
voidupdate(int rt, int a, int b, ll c){ // 【a, b】区间每个数+c,使用lazy if(tree[rt].l>=a && tree[rt].r<=b){ // 如果更新的区间 包含了 当前节点的区间 tree[rt].sum += (tree[rt].r-tree[rt].l+1)*c; tree[rt].add += c; return; }
push_down(rt); int mid = (tree[rt].l+tree[rt].r) >> 1; if(a <= mid) update(rt<<1, a, b, c); if(b > mid) update((rt<<1)+1, a, b, c); push_up(rt); }
ll quary(int rt, int a, int b){ // 查询【Na, Nb】区间和 if(tree[rt].l>=a && tree[rt].r<=b){ // 如果更新的区间 包含了 当前节点的区间 return tree[rt].sum; }
push_down(rt); ll ans = 0; int mid = (tree[rt].l+tree[rt].r) >> 1; if(a <= mid) ans += quary(rt<<1, a, b); if(b > mid) ans += quary((rt<<1)+1, a, b); return ans; }