Well, I was trying to solve this Flipping coins problem on Codechef. Am solving it with segment trees. But getting time limit exceed. I searched and found that I have to use lazy propagation. But I am unable to understand. My update function works recursively(top to bottom). Please give some hints or explain it with example. Also point out where I have to change the code.
In flipping coins, during update if a node value is 1 change it to 0 and if it is 0 change it to 1.
start and end are limits of original array. tree is segment tree array.
void update(int node, int start, int end,int pos)//pos=position to update
{
if(start==end) tree[node]=(tree[node]==0) ? 1 : 0;
else
{
int mid=(start+end)/2;
if(mid>=pos) update(2*node + 1, start, mid, pos);
else update(2*node + 2, mid+1, end, pos);
tree[node]=tree[2*node +1] + tree[2*node +2];
}
}
To mark only 5..15 as "yes", below is all you need. Only 7 nodes are involved in the operation, much less than what if you don't use lazy propagation. It can be proved that at most
2logn - 1
nodes may be involved, wheren
is the range.Without lazy propagation, segment tree isn't any better than plain array.
More details for how to implement is left to you. You should work it out by yourself.