Maximum bitwise pairs

3.2

8 votes
Advanced Data Structures, Dynamic Programming and Bit Masking, Advanced Algorithms, Algorithms, Dynamic Programming
Problem

You are given an array of N positive integers and Q queries. In each query, you are given an index i (1iN). Find an index j (1jN) such that (i & j)=0 and Ai+Aj is maximum. Find the maximum possible value Ai+Aj for each query. If no such index j exists, then the answer is 1

Note: Here, & is a bitwise AND operator.

Input format

  • The first line contains T denoting the number of test cases.
  • The first line of each test case contains an integer N denoting the number of array elements.
  • The next line contains N space-separated positive integers.
  • The next line contains an integer Q denoting the number of queries that must be performed.
  • Each of the next Q lines contains an integer i.

Output format

For each test case, print Q lines where the ith line must contain the output for the ith query.

Constraints

1T20

1N,Q105

1Ai109

1QiN

Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

In 1'st query, we can choose index 1, as (1 & 2) = 0 and (7 + 2) = 9 is maximum possible value we can get.
In 2'nd query, we can choose index 3, as (3 & 4) = 0 and (8 + 6) = 14 is maximum possible value we can get.

Editor Image

?