题意
给你
n
n
n个数,找到一个数使得这
n
n
n个数异或这个数后的得到的数的二进制下
1
1
1的个数相同。
这
n
n
n个数大小不超过
2
30
−
1
2^{30}-1
230−1
题解
首先我们可以知道找到这个数,这个数大小也不会超过
2
30
−
1
2^{30}-1
230−1,因为一旦超过,多余的都是相同的,没有意义。
那我们怎么处理呢,如果我们只处理前一半,得到一组前一半的异或结果
1
1
1的个数。
再处理后一半,得到一组后一半的异或结果
1
1
1的个数。
怎么判断合法与否呢?合法肯定是对于
n
n
n个前一半和后一半,相加全部相等。
怎么转换成能够编程的呢?
a
+
b
=
c
+
d
a+b=c+d
a+b=c+d,
a
−
c
=
−
(
b
−
d
)
a-c=-(b-d)
a−c=−(b−d)
所以处理前一半得到结果的差,再处理后一半的时候,查询这个差的相反数有没有出现过,出现过则为答案。
用
m
a
p
map
map直接可以记录。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e5+500;
int n,a[maxn];
map<vector<int>,int>mp;
int fun(int x){
int cnt=0;
while(x){
cnt+=x%2;
x/=2;
}
return cnt;
}
int main(){
cin>>n;
for(int i=1;i<=n;i++)cin>>a[i];
for(int i=0;i<(1<<15);i++){
vector<int>tmp,tp;
for(int j=1;j<=n;j++){
int b=i^(a[j]>>15);
tmp.push_back(fun(b));
}
for(int j=1;j<n;j++){
tp.push_back(tmp[j]-tmp[j-1]);
}
if(mp.count(tp))continue;
mp[tp]=i;
}
int ans=-1;
for(int i=0;i<(1<<15);i++){
vector<int>tmp,tp;
for(int j=1;j<=n;j++){
int b=i^a[j];
b=(b&((1<<15)-1));
tmp.push_back(fun(b));
}
for(int j=1;j<n;j++){
tp.push_back(tmp[j-1]-tmp[j]);
}
if(mp.count(tp)){
ans=(mp[tp]<<15)+i;
break;
}
}
cout<<ans<<endl;
}