- 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 9 15
Hint
-
The sums may exceed the range of 32-bit integers.
\
\
两种操作,
1.一段连续区间都加上一个数。
2.查询一段区间的数字之和。
第一次写区间修改,套错了模板,各种错误层出不穷,关键还是对线段树的理解不够深刻吧。
\
#include<iostream> #include<cstdio> #define ll long long #include<cstring> const int MX = 1e5+5; ll sum[4 * MX]; ll la[4 * MX]; void pushdown(int rt, int l, int r){ if(la[rt]){ int m = (l + r) / 2; la[2 * rt] += la[rt]; la[2 * rt + 1] += la[rt]; //两端更新 sum[2 * rt] += 1LL * (m - l + 1) * la[rt]; //是+= sum[2 * rt + 1] += 1LL * (r - m) * la[rt]; la[rt] = 0; } } void build(int l, int r, int rt){ if(l == r) { scanf("%I64d",&sum[rt]); return; } int m = (l + r) / 2; build(l, m, 2 * rt); build(m+1, r, 2 * rt +1); sum[rt] = sum[2 * rt] + sum[2 * rt + 1]; } void update (int st, int en, int co, int l, int r, int rt){ if(st <= l && r <= en){ sum[rt] += 1LL* (r - l + 1) * co; //这里错写成 l-r la [rt] += co; //+= 错写 = return ; } pushdown(rt, l, r); int m = (l + r) / 2; if(st <= m) update(st, en, co, l, m, 2 * rt); if(m < en) update(st, en, co, m+1, r, 2 * rt + 1); sum[rt] = sum[2 * rt] + sum[2 * rt + 1]; } ll sea(int st, int en, int l, int r, int rt){ if(st <= l && r <= en) return sum[rt]; int m = (l + r) /2 ; ll ans = 0; pushdown(rt, l, r); //pushdown不能省 if(st <= m) ans += sea(st, en, l, m, 2 * rt); if(m < en) ans += sea(st, en, m+1, r, 2 * rt + 1); return ans; } int main(){ int n,q,a,b,c; char cmd[3]; while(scanf("%d%d",&n,&q) != EOF){ build(1, n, 1); memset(la, 0, sizeof(la)); //差点sizeof(0); while(q--){ scanf("%s",cmd); if(cmd[0] == 'Q'){ scanf("%d%d",&a,&b); printf("%I64d\n",sea(a, b, 1, n, 1)); } else { scanf("%d%d%d",&a, &b, &c); update(a, b, c, 1, n, 1); } } } return 0; }
\
本文已参与「新人创作礼」活动,一起开启掘金创作之路