首页 > 代码库 > POJ 3468

POJ 3468

成段更新 easy

 1 #include <stdio.h> 2 #define lson l,mid,id<<1 3 #define rson mid+1,r,id<<1|1 4 const int MM = 100001; 5 __int64 num[MM<<2],lazy[MM<<2]; 6  7 void push_down(int l,int r,int id)   8 { 9     int mid=(l+r)>>1;10     num[id<<1]+=lazy[id]*(mid-l+1);11     num[id<<1|1]+=lazy[id]*(r-mid);12     lazy[id<<1]+=lazy[id];13     lazy[id<<1|1]+=lazy[id];14     lazy[id]=0;15 }16 void build_tree(int l,int r,int id)17 {18     if(l==r)19     {20         scanf("%I64d",&num[id]);21         return;22     }23     else24     {25         int mid=(l+r)>>1;26         build_tree(lson);27         build_tree(rson);28         num[id]=num[id<<1]+num[id<<1|1];29     }30 }31 32 void Update(int L,int R,int e,int l,int r,int id)33 {34     if(L<=l&&r<=R)35     {36         num[id]+=(r-l+1)*e;37         lazy[id]+=e;38         return;39     }40 41     if(lazy[id])push_down(l,r,id);42     int mid=(l+r)>>1;43     if(L<=mid)Update(L,R,e,lson);44     if(R>mid)Update(L,R,e,rson);45     num[id]=num[id<<1]+num[id<<1|1];46 }47 48 __int64 Query(int L,int R,int l,int r,int id)49 {50     if(L<=l&&r<=R)51     {52         return num[id];53     }54     55     __int64 ret=0;56     int mid=(l+r)>>1;57     if(lazy[id])58         push_down(l,r,id);59     if(L<=mid)ret+=Query(L,R,lson);60     if(R>mid)ret+=Query(L,R,rson);61     num[id]=num[id<<1]+num[id<<1|1];62     return ret;63 }64 int main()65 {66     int n,m,i,x,y,z;67     char ch[2];68     while(~scanf("%d %d",&n,&m))69     {70         build_tree(1,n,1);71         while(m--)72         {73             scanf("%s",ch);74             if(ch[0]==C)75             {76                 scanf("%d %d %d",&x,&y,&z);77                 Update(x,y,z,1,n,1);78             }79             else80             {81                 scanf("%d %d",&x,&y);82                 __int64 ans=Query(x,y,1,n,1);83                 printf("%I64d\n",ans );84             }85         }86 87     }88     return 0;89 }

 

POJ 3468