CF1721D Maximum AND

https://codeforces.com/problemset/problem/1721/D

Firsly, let’s consider finding the answer bit by bit, assuming the k k k non-zero digits of the answer as x 1 … x k x_1 \dots x_k x1xk. Then, for each value that we can acquire by reordering b b b, ( a i & v a l ) ⊕ ( b i & v a l ) = v a l (a_i \& val) \oplus (b_i \& val) = val (ai&val)(bi&val)=val must be satisfied, where the i i i non-zero bit of a a a and b b b will only remain to be one if the i i ith bit of v a l val val is also one.

Finally, since for a v a l val val that we can acquire, every number in [ 0 , v a l ) [0,val) [0,val) can also be acquired. Therefore, we can find the answer via binary search.

#include
#include
#include
#include
#include
using namespace std;
const int Maxn=1e5+10;
int a[Maxn],b[Maxn];
map <int,int> c;
int n;
inline int read()
{
	int s=0,w=1;
	char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
	while(ch>='0' && ch<='9')s=(s<<3)+(s<<1)+(ch^48),ch=getchar();
	return s*w;
}
bool check(int val)
{
	bool flag=1;
	for(int i=1;i<=n;++i)
	++c[a[i]&val];
	for(int i=1;i<=n;++i)
	{
		if(!c[(b[i]&val)^val]){flag=0;break;}
		else --c[(b[i]&val)^val];
	}
	for(int i=1;i<=n;++i)
	c[a[i]&val]=0;
	return flag;
}
int main()
{
	// freopen("in.txt","r",stdin);
	int T=read();
	while(T--)
	{
		n=read();
		for(int i=1;i<=n;++i)
		a[i]=read();
		for(int i=1;i<=n;++i)
		b[i]=read();
		int l=0,r=(1<<30)-1;
		while(l<r)
		{
			int mid=(l+r+1)>>1;
			if(check(mid))l=mid;
			else r=mid-1;
		}
		printf("%d\n",l);
	}
	return 0;
}

你可能感兴趣的:(题解,#Codeforces,c++,算法)