Best x for the largest XOR-sum
Given an array A and a limit K, find the x between 0 and K that makes (x XOR A[1]) + (x XOR A[2]) + … + (x XOR A[N]) as large as possible, and print that largest sum.
Reported in: Infosys (SP / DSE · earlier papers) (memory-based)
Input
First line: N and K. Second line: N integers.
Output
The largest XOR-sum.
Constraints
1 ≤ N ≤ 10^5; 0 ≤ K, A[i] ≤ 10^9.
Example 1
Input:
3 7
1 2 3
Output:
18Example 2
Input:
2 0
5 9
Output:
14Example 3
Input:
4 10
8 8 1 0
Output:
43Hint: Bit b of x adds 2^b times the number of A values that differ from x in that bit. Without a limit you set bit b exactly when most A values have a 0 there. With the limit, try x = K and, for each 1 bit of K, x = K’s higher bits, a 0 at that bit, and the best free choice below it.