C语言线段树(3)___A Simple Problem with Integers(hdu 3468)

来源:互联网 发布:移动端域名配置 编辑:程序博客网 时间:2024/05/21 07:42

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 abc" means adding c to each of AaAa+1, ... , Ab. -10000 ≤ c ≤ 10000.
"Q ab" 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



题意:给出n个数的初始值和m条命令, 每条命令由 一个字符和 若干个数字组成. 若字符为C 那么后面跟着三个数字分别为 l,r,step,表示在区间 [ l , r ] 的每个数加上step,如果是Q,那么后面跟着两个数字分别为 l , r .输出区间 [ l , r ]的数字和.


代码“:

#include <cstdio>#include <cstring>#define maxn 100010using namespace std;struct node{int left,right;    long long lazy,sum;    int mid(){        return (left+right)>>1;    }}tree[maxn*4]; void CreatBtree(int l,int r,int rt){    tree[rt].left=l;    tree[rt].right=r;    tree[rt].lazy=0;     //cout<<l<<" "<<r<<endl;    if(l==r){        scanf("%lld",&tree[rt].sum);        return;    }    int mid=tree[rt].mid();    CreatBtree(l,mid,rt<<1);    CreatBtree(mid+1,r,rt<<1|1);    tree[rt].sum=tree[rt<<1].sum+tree[rt<<1|1].sum;}void change(int rt,int l,int r,int step){    if(l==tree[rt].left && r==tree[rt].right){    tree[rt].lazy+=step;return; }tree[rt].sum+=(long long)step*(r-l+1);int mid=tree[rt].mid();if(r<=mid) change(rt<<1,l,r,step);else if(l>mid)change(rt<<1|1,l,r,step);else{change(rt<<1,l,mid,step);change(rt<<1|1,mid+1,r,step);}}long long Query(int rt,int l,int r){    if(tree[rt].left==l && tree[rt].right==r)return tree[rt].sum+(r-l+1)*tree[rt].lazy;    if(tree[rt].lazy!=0){    tree[rt<<1].lazy+=tree[rt].lazy;tree[rt<<1|1].lazy+=tree[rt].lazy;tree[rt].sum+=(long long)(tree[rt].right-tree[rt].left+1)*tree[rt].lazy;  tree[rt].lazy=0; }     if(r<=tree[rt].mid()) return Query(rt<<1,l,r);    else if(l>tree[rt].mid())return Query(rt<<1|1,l,r);    else        return Query(rt<<1,l,tree[rt].mid())+Query(rt<<1|1,tree[rt].mid()+1,r);}int main(){    int i,j,n,m,k,l,r,step;    char ch;    while(scanf("%d%d",&n,&m)!=EOF){        CreatBtree(1,n,1);        //printf("%d %d %d\n",tree[1].max,tree[1].left,tree[1].right);         for(i=0;i<m;i++){        scanf("%s%d%d",&ch,&l,&r);        if(ch=='Q')printf("%lld\n",Query(1,l,r));        else{        scanf("%d",&step);        change(1,l,r,step);}}    }    return 0;}


0 0