Question

I recently read about lazy propogation in segment tree and coded it too.But i got stuck when suppose instead of adding value(=val) i need to divide by value.How to do it ? Please help

My update function is as follow :

void update_tree(int node, int a, int b, int i, int j, int value) { 
if(lazy[node] != 0) { // This node needs to be updated
tree[node] += lazy[node]; // Update it

if(a != b) {
lazy[node*2] += lazy[node]; // Mark child as lazy
lazy[node*2+1] += lazy[node]; // Mark child as lazy
}

lazy[node] = 0; // Reset it
}
if(a > b || a > j || b < i) // Current segment is not within range [i, j]
return;
if(a >= i && b <= j) { // Segment is fully within range
tree[node] += value;

if(a != b) { // Not leaf node
lazy[node*2] += value;
lazy[node*2+1] += value;
}

return;
}

update_tree(node*2, a, (a+b)/2, i, j, value); // Updating left child
update_tree(1+node*2, 1+(a+b)/2, b, i, j, value); // Updating right child

tree[node] = max(tree[node*2], tree[node*2+1]); // Updating root with max value
}
Was it helpful?

Solution

HINTS

Suppose you need to divide by a fixed value of K.

One possibility would be to convert your numbers to base K and in each node maintain an array of numbers A[], where A[i] is the total in all lower nodes of all digits in position i (when thought of as a base K number).

So, for example, if K was 10, then A[0] would store the total of all the units, while A[1] would store the total of all the tens.

The reason to do this is that it then becomes easy to divide lazily by K, all you need to do is set A[i]=A[i+1] and you can use the same lazy update trick as in your code.

EXAMPLE

Suppose we had an array 5,11,20,100 and K was 10

We would construct a node for element 5,11 containing the value:

Total = A[1]*10+A[0]*1 with A[1]=1 and A[0]=5+1 (the sum of the unit values)

we would also have a node for 20,100 containing the value:

Total = A[2]*100+A[1]*10+A[0]*1 with A[2]=1,A[1]=2,A[0]=0

and a node for the entire 5,11,20,100 array with:

Total = A[2]*100+A[1]*10+A[0]*1 with A[2]=1,A[1]=2+1,A[0]=5+1

If we then wanted to divide the whole array by 10, we would simply change the array elements for the top node:

A=[1,3,6] changes to [0,1,3]

and then we could query the sum of all the node by computing:

Total = A[2]*100+A[1]*10+A[0]*1 = 0*100+1*10+3*1=13

which is the same as

(5/10=0)+(11/10=1)+(20/10=2)+(100/10=10)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top