I participated in one algorithmic competition. I got stuck in one problem, I am asking the same here.
Problem Statement
XOR-sum of a sub-array is to XOR all the numbers of that sub-array. An array is given to you, you have to add all possible such XOR-sub-array.
Example
Input
Array :- 1 2
Output :- 6
Explanation
F(1, 1) = A[1] = 1, F(2, 2) = A[2] = 2 and F(1, 2) = A[1] XOR A[2] = 1 XOR 2 = 3. Hence the answer is 1 + 2 + 3 = 6.
I found an $O(N^2)$ solution, but it was too inefficient one and wasn't accepted in the competition.
I saw the best solution of this problem on Code Chef. But in this code, I didn't understand below module, please help me to understand that.
for (int i=0, p=1; i<30; i++, p<<=1) {
int c=0;
for (int j=0; j<=N; j++) {
if (A[j]&p) c++;
}
ret+=(long long)c*(N-c+1)*p;
}
In pseudocode:
- Set $r = 0$
- For $i$ from $0$ to $29$, let $p = 2^i$.
- Set $c=0$
- Iterate over the array $A$. For each element $A[j]$:
- If $A[j] \mathbin\& p \ne 0$ then increment $c$. ($\&$ is bitwise and.)
- Add $c \times (N-c+1) \times p$ to $r$