2

I have an Array A(size <= 10^5) of numbers(<= 10^8), and I need to answer some queries(50000), for L, R, how many subsets for elements in the range [L, R], the XOR of the subset is a number that has 0 or 1 bit set(power of 2). Also, point modifications in the array are being done in between the queries, so can't really do some offline processing or use techniques like square root decomposition etc.

I have an approach where I use DP to calculate for a given range, something on the lines of this: https://www.geeksforgeeks.org/count-number-of-subsets-having-a-particular-xor-value/

But this is clearly too slow. This feels like a classical segment tree problem, but can't seem to find as to what data points to store at each node, so that I can use the left child and right child to compute the answer for the given range.

John Doe
  • 21
  • 1
  • 1
    Please supply an example. When you say "subsets," what exactly do you mean? If the range is `[2, 10]`, is `[3,4,5]` a subset? Is `[2,4,6,8]` a subset? – Jim Mischel Mar 26 '20 at 17:40

1 Answers1

1

Yeah, that DP won't be fast enough.

What will be fast enough is applying some linear algebra over GF(2), the Galois field with two elements. Each number can be interpreted as a bit-vector; adding/subtracting vectors is XOR; scalar multiplication isn't really relevant.

The data you need for each segment is (1) how many numbers are there in the segment (2) a basis for the subspace of numbers generated by numbers in the segment, which will consist of at most 27 numbers because all numbers are less than 2^27. The basis for a one-element segment is just that number if it's nonzero, else the empty set. To find the span of the union of two bases, use Gaussian elimination and discard the zero vectors.

Given the length of an interval and a basis for it, you can count the number of good subsets using the rank-nullity theorem. Basically, for each target number, use your Gaussian elimination routine to test whether the target number belongs to the subspace. If so, there are 2^(length of interval minus size of basis) subsets. If not, the answer is zero.

David Eisenstat
  • 64,237
  • 7
  • 60
  • 120