I participated in one algorithmic competition. I got stuck in one problem, I am asking the same here.
Problem Statement
XOR-sum array is to XOR
Think of the numbers arranged in a Nx32 matrix, where each row represents a number in array and each column represents i'th bits of all the numbers. Now, effects of XOR operation are confined within a column. Therefore, we can separate each column, calculate the XOR-sum for that column and add it to the result.
I have separated a column. How to calculate XOR-sum within this column?
For this purpose, we count the number of 1 in this column. Let c
denote the number of 1 in a column. Then, number of 0 will be N - c
. To produce 1 in column result (0s have no effect on final result), for each 1 from c
, we can take a 0 from N - c
, or take no 0 at all. Therefore, there are N - c + 1
ways for each 1 to produce 1 after XOR operation. As there are c
1s, Total number of 1 after XOR operation is c * (N - c + 1)
.
Each column contributes differently to the final result with respect to there position i
. Therefore, multiply column-result with 2^i
(1 << i
) and add this to final result.
for (int i=0, p=1; i<30; i++, p<<=1)
p = 1 << i
.if (A[j]&p) c++;
ret+=(long long)c*(N-c+1)*p;
p = 1 << i
(= 2^i).CONFESSION: I only explained what is done in the code. I have no proof that this will cover all the sub-arrays.