区间树 [成段更新] POJ 3468 A Simple Problem with Integers

来源:互联网 发布:淘宝在线考试答案 编辑:程序博客网 时间:2024/05/17 08:18

可参考这个题

http://blog.csdn.net/gaotong2055/article/details/9300141


Description

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



#include <iostream>#include <stdio.h>using namespace std;int n,q;long long tree[400000];long long add[400000];int a,b,c;void build(int l, int r, int k){add[k] = 0;if(l==r){scanf("%lld", &tree[k]);return;}int m = (l+r)/2;build( l, m, 2*k);build( m+1, r, 2*k + 1);tree[k] = tree[2*k] + tree[2*k+1];}void down(int k,int m){if(add[k]){add[k*2+1] += add[k];add[k*2] += add[k];tree[k*2] += (m-m/2) * add[k];tree[k*2+1] += (m/2) * add[k];add[k] = 0;}}void update(int l,int r, int k){if( a <= l && b >= r){ //找到合适的区间add[k] += c;tree[k] += (long long)(r - l + 1) * c;return;}down(k, r-l+1); //更新子树int m = (l+r)/2;if(a <= m) update(l, m, 2*k);if(b > m) update(m+1, r, 2*k+1);tree[k] = tree[2*k] + tree[2*k+1];}long long query(int l, int r, int k){if(a <= l &&  b >= r){return tree[k];}down(k, r-l+1); //查询的时候需要更新子树long long ans = 0;int m = (l+r)/2;if(a <= m)ans += query(l , m, k*2);if(b > m)ans += query(m+1, r, k*2+1);return ans;}int main() {//freopen("in.txt", "r", stdin);char cmd[5];while(scanf("%d %d", &n, &q) != EOF){build(1, n ,1);while(q--){scanf("%s", cmd);if(cmd[0] == 'Q'){scanf("%d %d",&a,&b);printf("%lld\n", query(1,n,1));}else{scanf("%d %d %d",&a, &b, &c);update(1, n, 1);}}}return 0;}




原创粉丝点击