Question

I have a good idea on how this structure works and how to update it, however when it comes to work with Lazy Propagation I don't know what to do, as many many many problems requires this to pass in competitions I want to know how to make it work.

I am trying this problem on spoj: http://www.spoj.com/problems/CDC12_H/

If somebody can explain me how the lazy propagation can be adapted to this situation I will take that and work on the idea, I really don't want to post my code because the idea for me is to make this work by myself but with a little help.

I hope someone comes with the solution to my problem.

Was it helpful?

Solution

This is my snippet of segment tree implementation with lazy propagation. Hope this will help you.

#define int long long
#define MAX 100005*3

int  stree[MAX],lazy[MAX];

void update(int  cur,int  cur_lft,int  cur_rgt,int  st,int  en,int  val)
{
    if(cur_lft>en || cur_rgt<st) return ;
    if(cur_lft>=st && cur_rgt<=en)
    {
        stree[cur]+=val*(cur_rgt-cur_lft+1);
        lazy[cur]+=val;
        return;
    }
    int  l=cur<<1,r=(cur<<1)+1,mid=(cur_lft+cur_rgt)>>1;
    update(l,cur_lft,mid,st,en,val);
    update(r,mid+1,cur_rgt,st,en,val);
    stree[cur]=stree[l]+stree[r]+lazy[cur]*(cur_rgt-cur_lft+1);
}

int  query(int  cur,int  cur_lft,int  cur_rgt,int  st,int  en,int  lzy)
{
    if(cur_lft>en || cur_rgt<st) return 0;
    if(cur_lft>=st && cur_rgt<=en) return stree[cur]+lzy*(cur_rgt-cur_lft+1);
    int  l=cur<<1,r=(cur<<1)+1,mid=(cur_lft+cur_rgt)>>1;
    int  left_tree=query(l,cur_lft,mid,st,en,lzy+lazy[cur]);
    int  right_tree=query(r,mid+1,cur_rgt,st,en,lzy+lazy[cur]);
    return left_tree+right_tree;
}

Edit To update and query into segment tree we can call following functions:

query(1,0,n-1,lower_range,upper_range,0));
update(1,0,n-1,lower_range,upper_range,v);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top