D. Maximum AND
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given two arrays aa and bb, consisting of nn integers each.
Let's define a function f(a,b)f(a,b) as follows:
- let's define an array cc of size nn, where ci=ai⊕bici=ai⊕bi (⊕⊕ denotes bitwise XOR);
- the value of the function is c1&c2&⋯&cnc1&c2&⋯&cn (i.e. bitwise AND of the entire array cc).
Find the maximum value of the function f(a,b)f(a,b) if you can reorder the array bb in an arbitrary way (leaving the initial order is also an option).
Input
The first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.
The first line of each test case contains one integer nn (1≤n≤1051≤n≤105) — the size of arrays aa and bb.
The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai<2300≤ai<230).
The third line contains nn integers b1,b2,…,bnb1,b2,…,bn (0≤bi<2300≤bi<230).
The sum of nn over all test cases does not exceed 105105.
---------------------------------------------------------------------------------------------------------------------------------
考虑对答案的每一位进行考虑,若答案pos位置为1,那么全部ci这一位置都为1,也就是1--n的ai!=bi,贪心选取,由高到低 。能添加这一位置时,必定要添加。那么如何判断这一位是否能添加呢?
条件也就是 B数组即为 A数组所需,不多不少,正正好好。例如 111 为我们最终答案的时候
A数组如果是 000 010 011 111
其所需数组就是111 101 100 000
容易发现所需数组就是 将A数组这几个位置提取出来,然后取反即可,提取操作为 a[i]&x
取反操作为 (a[i]&x)^x
那么B再将B数组进行提取即可 b[i]&x
快速判断两个集合是否等价,一个技巧就是进行vector容器排序 ,排序之后直接比较是否相等即可
# include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int n,a[100000+10],b[100000+10];
bool check(int now)
{
vector<int>temp1,temp2;
for(int i=1;i<=n;i++)
{
temp1.push_back(((a[i]&now)^now));
temp2.push_back((b[i]&now));
}
sort(temp1.begin(),temp1.end());
sort(temp2.begin(),temp2.end());
return temp1==temp2;
}
int main()
{
int t;
cin>>t;
while(t--)
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
for(int i=1;i<=n;i++)
{
cin>>b[i];
}
int ans=0;
for(int i=30;i>=0;i--)
{
if(check((ans|(1<<i))))
{
ans|=(1<<i);
}
}
cout<<ans<<endl;
}
return 0;
}