1. 程式人生 > >線段樹(帶lazy)

線段樹(帶lazy)

ret val max pos void segment 所有 color amp

帶lazy主要為了節省不必要的時間

給一段修改區間值,區間求和模板

將區間[l,r]的所有數修改為v,求區間[l,r]的和

 1 struct Segment_tree{
 2     int L[maxn*4],R[maxn*4],val[maxn*4],add[maxn*4];
 3 
 4     void lazy(int pos){ //懶惰標記
 5         val[pos<<1] = add[pos]*(R[pos<<1] - L[pos<<1] + 1);
 6         val[pos<<1|1] = add[pos]*(R[pos<<1
|1] - L[pos<<1|1] + 1); 7 add[pos<<1] = add[pos]; 8 add[pos<<1|1] = add[pos]; 9 add[pos] = 0; 10 } 11 12 void build(int pos,int l,int r,int *num){ 13 L[pos] = l; 14 R[pos] = r; 15 add[pos] = 0; 16 if(l == r){ 17 val[pos] = num[l];
18 return; 19 } 20 int mid = (l+r) >> 1; 21 build(pos<<1,l,mid,num); 22 build(pos<<1|1,mid+1,r,num); 23 val[pos] = val[pos<<1]+val[pos<<1|1]; 24 } 25 26 void update(int pos,int l,int r,int v){ 27 if(L[pos] == l&&R[pos] == r){
28 val[pos] = v*(r-l+1); 29 add[pos] = v; 30 return; 31 } 32 if( add[pos] ) lazy(pos); //下放 33 int mid = (L[pos]+R[pos]) >> 1; 34 if(r <= mid){ 35 update(pos<<1,l,r,v); 36 } 37 else if(l > mid){ 38 update(pos<<1|1,l,r,v); 39 } 40 else{ 41 update(pos<<1,l,mid,v); 42 update(pos<<1|1,mid+1,r,v); 43 } 44 val[pos] = val[pos<<1] + val[pos<<1|1]; 45 } 46 47 int query(int pos,int l,int r){ 48 if(L[pos] == l && R[pos] == r){ 49 return val[pos]; 50 } 51 if( add[pos] ) lazy(pos); //下放 52 int mid = (L[pos] + R[pos]) >> 1; 53 if(r <= mid) return query(pos<<1,l,r); 54 else if(l > mid) return query(pos<<1|1,l,r); 55 else{ 56 return query(pos<<1,l,mid)+query(pos<<1|1,mid+1,r); 57 } 58 } 59 }tre;

線段樹(帶lazy)