Problem 676
Maximum XOR With an Element From Array
Hard · 30 pts · Bit Manipulation, Trie, Sorting
Problem
You are given an array NUMS and Q queries. Query (X, M) asks for the largest value of X XOR NUMS[j] over all elements with NUMS[j] <= M, or -1 if no element is at most M. Answer the queries offline: sort them by M and the array ascending, insert elements into a binary trie of 30-bit numbers while they are at most the current M, then walk the trie greedily choosing the opposite bit of X whenever it exists.
Input
The first line contains N and Q. The second line contains NUMS. Each of the next Q lines contains X and M.
Output
Print the answers to the queries, one per line, in input order.
Constraints
1 <= N, Q <= 100000; 0 <= NUMS[j], X, M <= 10^9
Example input
5 3 0 1 2 3 4 3 1 1 3 5 6
Example output
3 3 7
Explanation
With NUMS = 0 1 2 3 4: the query (3, 1) can use 0 or 1, and 3 XOR 0 = 3 is the best. The query (1, 3) can use 0 to 3, and 1 XOR 2 = 3 is the best. The query (5, 6) can use everything, and 5 XOR 2 = 7 is the best.