您需要的是高斯消除。
例如:3 数字{9, 8, 5}
先按降序排序,再转成二进制:
9 : 1001
8 : 1000
5 : 0101
观察第一个数字。最高位为 4。
现在检查 1st 数字 (9) 的 4th 位。因为它是 1,所以将第 4 位为 1 的数字与其余数字异或。
9 : 1001
1 : 0001 > changed
5 : 0101
现在检查2nd 数字 (1) 的 3rd 位。因为它是 0,所以检查下面的其余数字,其中 3rd 位是 1。
数字 5 在3rd 位中有 1。交换它们:
9 : 1001
5 : 0101 > swapped
1 : 0001 >
现在 xor 5 与 3rd 位为 1 的其余数字。这里不存在。所以不会有任何变化。
现在检查3rd 数字 (1) 的 2nd 位。因为它是 0,并且在第 2 位为 1 的位置下面没有其他数字,所以不会有任何变化。
现在检查 3rd 数字 (1) 的 1st 位。因为它是 1,所以更改 1st 位为 1 的其余数字。
8 : 1000 > changed
4 : 0100 > changed
1 : 0001
不用再考虑了:)
现在异或整个剩余数组{8 ^ 4 ^ 1} = 13
所以13 是解决方案:)
这就是使用高斯消元法解决问题的方法 :)
这是我的 C++ 实现:
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
ull check_bit(ull N,int POS){return (N & (1ULL<<POS));}
vector<ull>v;
ull gaussian_elimination()
{
int n=v.size();
int ind=0; // Array index
for(int bit=log2(v[0]);bit>=0;bit--)
{
int x=ind;
while(x<n&&check_bit(v[x],bit)==0)
x++;
if(x==n)
continue; // skip if there is no number below ind where current bit is 1
swap(v[ind],v[x]);
for(int j=0;j<n;j++)
{
if(j!=ind&&check_bit(v[j],bit))
v[j]^=v[ind];
}
ind++;
}
ull ans=v[0];
for(int i=1;i<n;i++)
ans=max(ans,ans^v[i]);
return ans;
}
int main()
{
int i,j,k,l,m,n,t,kase=1;
scanf("%d",&n);
ull x;
for(i=0;i<n;i++)
{
cin>>x;
v.push_back(x);
}
sort(v.rbegin(),v.rend());
cout<<gaussian_elimination()<<"\n";
return 0;
}