Let AND denote the bitwise AND operation, and OR denote the bitwise OR operation.
You are given an array a a a of length n and a non-negative integer k k k. You can perform at most k k k operations on the array of the following type:
- Select an index i ( 1 ≤ i ≤ n ) i (1≤i≤n) i(1≤i≤n) and replace a i a_i ai with a i a_i ai OR 2 j 2^j 2j where j j j is any integer between 0 0 0 and 30 30 30 inclusive. In other words, in an operation you can choose an index i ( 1 ≤ i ≤ n ) i (1≤i≤n) i(1≤i≤n) and set the j j j-th bit of a i a_i ai to 1 ( 0 ≤ j ≤ 30 ) 1 (0≤j≤30) 1(0≤j≤30).
Output the maximum possible value of a 1 a_1 a1 AND a 2 a_2 a2 AND … AND a n a_n an after performing at most k k k operations.
Input
The first line of the input contains a single integer t ( 1 ≤ t ≤ 100 ) t (1≤t≤100) t(1≤t≤100) — the number of test cases. The description of test cases follows.
The first line of each test case contains the integers n n n and k ( 1 ≤ n ≤ 2 ⋅ 1 0 5 , 0 ≤ k ≤ 1 0 9 ) k (1≤n≤2⋅10^5, 0≤k≤10^9) k(1≤n≤2⋅105,0≤k≤109).
Then a single line follows, containing n n n integers describing the arrays a ( 0 ≤ a i < 2 31 ) a (0≤a_i<2^{31}) a(0≤ai<231).
It is guaranteed that the sum of n n n over all test cases does not exceed 2 ⋅ 1 0 5 2⋅10^5 2⋅105.
Output
For each test case, output a single line containing the maximum possible AND value of a 1 a_1 a1 AND a 2 a_2 a2 AND … AND a n a_n an after performing at most k k k operations.
Example
input4 3 2 2 1 1 7 0 4 6 6 28 6 6 12 1 30 0 4 4 3 1 3 1
output
2 4 2147483646 1073741825
Note
For the first test case, we can set the bit 1 ( 2 1 ) 1 (2^1) 1(21) of the last 2 2 2 elements using the 2 2 2 operations, thus obtaining the array [ 2 , 3 , 3 ] [2, 3, 3] [2,3,3], which has AND value equal to 2 2 2.
For the second test case, we can’t perform any operations so the answer is just the AND of the whole array which is 4 4 4.
题目大意
可以进行 k k k 次操作,将数组 a a a 中的一个数 OR 一个 2 j 2^j 2j (等价于在该数对应的二进制第 j j j 位变成 1 1 1), k k k 次操作后使得数组 a a a 中所有数 AND 后最大,并输出。
解题思路
在输入的时候我们可以把每个数对应二进制位为 1 1 1 的进行计数,因为要 AND 后最大,所以我们尽量使二进制较高位且数量较多的数进行 OR 操作,使其的数量达到 n n n (达到数组个数 AND 这一位才有效,也就是尽量使得在某一位 OR 上 0 0 0~ k k k 次后的数量达到 n n n),最后把二进制对应位的数量达到 n n n 的为 1 1 1 ,否则为 0 0 0 ,然后转化为十进制就是我们要的答案。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t; cin>>t;
while(t--)
{
int n, k; cin>>n>>k;
int bit[31] = {0};
for(int i=0; i<n; i++)
{
int x; cin>>x;
//记录所有数对应二进制对应位为 1 的个数
for(int j=0; j<31; j++)
if((x>>j) & 1) bit[j]++;
}
for(int i=30; i>=0; i--)
{
//尽量将二进制较高位为 1 的数量补充到 n
if(bit[i]+k >= n)
{
k -= n-bit[i];
bit[i] = n;
}
if(!k) break;
}
int ans = 0;
//将二进制转化为十进制
for(int i=0; i<31; i++) //数量达到 n 的为 1 ,否则为 0
if(bit[i] == n) ans |= (1<<i);
cout<<ans<<'\n';
}
return 0;
}