POJ3468 A Simple Problem with Integers(线段树区间修改)

来源:互联网 发布:神通数据库 7.0 下载 编辑:程序博客网 时间:2024/06/04 19:51

You have N integers, A1A2, ... , 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 A1A2, ... , AN. -1000000000 ≤ Ai ≤ 1000000000.
Each of the next Q lines represents an operation.
"C a b c" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q a b" means querying the sum of AaAa+1, ... , Ab.

Output

You need to answer all Q commands in order. One answer in a line.

Sample Input
10 51 2 3 4 5 6 7 8 9 10Q 4 4Q 1 10Q 2 4C 3 6 3Q 2 4
Sample Output
455915
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-rla [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;} 


阅读全文
0 0
原创粉丝点击