0

In an integer array (size 10^5) the operations are like these...

  1. Do bitwise xor operation with every element from index L to R by a particular number X
  2. Find the sum of the numbers from index L to R.

How can i do it with segment tree and lazy propagation ?

OmG
  • 18,337
  • 10
  • 57
  • 90
palatok
  • 1,022
  • 5
  • 20
  • 30

2 Answers2

2

I'd keep, on each node, 32 integers telling me how many ones are there in each position of the binary representation of the child nodes.

To XOR a segment node, it's just a matter of inverting how many ones are there in each position (for each bit 1 in X).

for i in range(32):
    if X&(1<<i):
        N[i] = (R-L+1)-N[i]. 

To calculate the sum,

s = 0
for i in range(32):
    s |= ((N[i]+carry)%2) << i
    carry = (N[i]+carry)/2
Juan Lopes
  • 10,143
  • 2
  • 25
  • 44
  • i don't understand this line... N[i] = (R-L+1)-N[i]. why would i subtract N[i] ? – palatok Nov 13 '12 at 00:20
  • To invert the number of 1's in the segment. Suppose we have a segment from 3 to 7 with 2 ones. This means that xor'ing it with a bit 1 will invert this number, i.e., all the ones become zeroes and all the zeroes become one. 7-3+1 -2 = 5 -2 = 3 – Juan Lopes Nov 13 '12 at 12:24
1

Your answer is not correct. You need to do some sort of lazy update like here: http://p--np.blogspot.ro/2011/07/segment-tree.html . Else, if you do update(1,n, x) and query(4,5) you will get a wrong answer because the update has changed just the root node.