首页 > 代码库 > HIHO线段树(成段)

HIHO线段树(成段)

 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 int 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<<1|1]=lazy[id];13     lazy[id]=0;14 }15 void build_tree(int l,int r,int id)16 {17     lazy[id]=0;18     if(l==r)19     {20         scanf("%d",&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     if(lazy[id])push_down(l,r,id);41     int mid=(l+r)>>1;42     if(L<=mid)43         Update(L,R,e,lson);44     if(R>mid)45         Update(L,R,e,rson);46     num[id]=num[id<<1]+num[id<<1|1];47 48 }49 int Query(int L,int R,int l,int r,int id)50 {51     if(L<=l&&r<=R)52     {53         return num[id];54     }55     if(lazy[id])push_down(l,r,id);56     int mid=(l+r)>>1;57     int ret=0;58     if(L<=mid)ret+=Query(L,R,lson);59     if(R>mid)ret+=Query(L,R,rson);60     num[id]=num[id<<1]+num[id<<1|1];61     return ret;62 }63 int main()64 {65     int n,m,op,x,y,z;66     scanf("%d",&n);67     build_tree(1,n,1);68     scanf("%d",&m);69     while(m--)70     {71         scanf("%d",&op);72         if(op==1)73         {74             scanf("%d %d %d",&x,&y,&z);75             Update(x,y,z,1,n,1);76         }77         else 78         {79             scanf("%d %d",&x ,&y);80             int ans=Query(x,y,1,n,1);81             printf("%d\n",ans );82         }83     }84 }

 

HIHO线段树(成段)