區間修改,區間求和 線段樹
阿新 • • 發佈:2018-11-27
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
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 9 15
Hint
The sums may exceed the range of 32-bit integers.
#include<iostream> #include<cstdio> #include<string> #include<cmath> #include<cstring> #include<algorithm> #define lson id<<1,l,mid #define rson id<<1|1,mid+1,r #define L id<<1 #define R id<<1|1 using namespace std; const int maxn = (int)2e5 + 10; typedef long long ll; struct node { ll lazy,sum; int left, right; void update(int x) { sum += 1ll * (right - left + 1)*x; lazy += x; } int mid() { return (left + right) >> 1; } }tree[maxn<<2|1]; void pushup(int id) { tree[id].sum = tree[L].sum + tree[R].sum; } void pushdown(int id) { int lazyval = tree[id].lazy; if (lazyval) { tree[L].update(lazyval); tree[R].update(lazyval); tree[id].lazy = 0; } } void build(int id, int l, int r) { tree[id].left = l, tree[id].right=r; tree[id].lazy = 0; if (l == r) { scanf("%lld",&tree[id].sum); } else { int mid = tree[id].mid(); build(lson); build(rson); pushup(id); } } void update(int id,int l,int r,int val) { if (l <= tree[id].left&&tree[id].right <= r) tree[id].update(val); else { pushdown(id); int mid = tree[id].mid(); if (mid >= l)update(L, l, r, val); if (r > mid) update(R, l, r, val); pushup(id); } } ll query(int id, int l, int r) { if (l <= tree[id].left&&tree[id].right <= r) return tree[id].sum; else { pushdown(id); ll res = 0; int mid = tree[id].mid(); if (mid >= l) res+=query(L, l, r); if(r>mid) res+=query(R, l, r); pushup(id); return res; } } int main() { int n, m,a,b,c; string s; scanf("%d%d", &n, &m); build(1,1,n); while (m--) { cin >> s; if (s[0] == 'Q') { scanf("%d%d",&a,&b); cout << query(1, a, b) << endl; } else if (s[0]=='C') { scanf("%d%d%d", &a, &b,&c); update(1,a,b,c); } } return 0; }