线段树 hdu3468  A Simple Problem…

来源:互联网 发布:cp雾化器做芯数据 编辑:程序博客网 时间:2024/06/08 20:50
A Simple Problem with Integers
Time Limit: 5000MSMemory Limit: 131072KTotal Submissions: 22668Accepted: 6080Case Time Limit: 2000MS

Description

Youhave N integers, A1A2,... , AN. You need to deal withtwo kinds of operations. One type of operation is to add some givennumber to each number in a given interval. The other is to ask forthe sum of numbers in a given interval.

Input

The first line contains twonumbers N and Q.1 ≤ N,Q ≤100000.
The second linecontains N numbers, theinitial valuesof A1A2,... , AN. -1000000000≤ Ai ≤1000000000.
Each of the next Q linesrepresents an operation.
"C a b c"means adding c to eachof AaAa+1,... , Ab. -10000≤ c ≤ 10000.
"Q a b" meansquerying the sumof AaAa+1,... , Ab.

Output

You need to answerall 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

55 
15

Hint

The sums may exceed the range of 32-bitintegers.
#include<stdio.h>
#define L(x) x<<1
#define R(x)(x<<1)+1
struct node
{

    intl,r;
    __int64 sum,add;//用于标记下传,否则必TLE
   
}t[100001*4];
int num[100001];
int n,q;
void build(int l,int r,int x)
{

   t[x].l=l;
   t[x].r=r;
   t[x].add=0;
   if(l==r)
   {

      t[x].sum=num[l];
       return ;
   }
    intmid=(t[x].l+t[x].r)/2;
   build(l,mid,L(x));
   build(mid+1,r,R(x));
   t[x].sum=t[L(x)].sum+t[R(x)].sum;
}

void Update(int l,int r,int x,int c)
{

   if(l<=t[x].l&&r>=t[x].r)
   {

      t[x].add+=c;
      t[x].sum+=c*(t[x].r-t[x].l+1);
       return ;

   }

   if(t[x].add)
   {

      t[L(x)].add+=t[x].add;
      t[L(x)].sum+=t[x].add*(t[L(x)].r-t[L(x)].l+1);
      t[R(x)].add+=t[x].add;
      t[R(x)].sum+=t[x].add*(t[R(x)].r-t[R(x)].l+1);
      t[x].add=0;

   }

    intmid=(t[x].l+t[x].r)/2;
   if(r>mid)Update(l,r,R(x),c);
   if(l<=mid) Update(l,r,L(x),c);   
   t[x].sum=t[L(x)].sum+t[R(x)].sum;

}

__int64  query(int l,int r,intx)
{

   if(l<=t[x].l&&r>=t[x].r)
               returnt[x].sum;
   if(t[x].add)
   {

      t[L(x)].add+=t[x].add;
      t[L(x)].sum+=t[x].add*(t[L(x)].r-t[L(x)].l+1);
      t[R(x)].add+=t[x].add;
      t[R(x)].sum+=t[x].add*(t[R(x)].r-t[R(x)].l+1);
      t[x].add=0;

   }

     intmid=(t[x].l+t[x].r)/2;
   if(r<=mid) 
return query(l,r,L(x));
    else if(l>mid) 
return query(l,r,R(x));
   else
    returnquery(l,mid,L(x))+query(mid+1,r,R(x));

}

int main()
{

int i;
   while(scanf("%d%d",&n,&q)!=EOF)
   {

      for(i=1;i<=n;i++) 
scanf("%d",&num[i]);
      build(1,n,1);
      for(i=1;i<=q;i++)
       {
          char str[10];
          int a,b,c;
          scanf("%s",str);
          if(str[0]=='Q')
          {
             scanf("%d%d",&a,&b);
             printf("%I64d\n",query(a,b,1));
          }
          else
          {
             scanf("%d%d%d",&a,&b,&c);
             Update(a,b,1,c);
          }
       }
   }
    return0;

}