Gaussian Elimination is what you need.
For example : 3
numbers {9, 8, 5}
First sort them in decreasing order and convert them into binary :
9 : 1001
8 : 1000
5 : 0101
Observe the 1st number. Highest bit is 4.
Now check 4th
bit of the 1st
number (9). As it is 1, xor the number with the rest of the numbers where 4th bit is 1.
9 : 1001
1 : 0001 > changed
5 : 0101
Now check 3rd
bit of 2nd
number (1). As it is 0, check rest of the below numbers where 3rd
bit is 1.
Number 5 has 1 in 3rd
bit. Swap them :
9 : 1001
5 : 0101 > swapped
1 : 0001 >
Now xor 5 with the rest of the numbers where 3rd
bit is 1. Here none exists. So there will be no change.
Now check 2nd
bit of 3rd
number (1). As it is 0 and there is no other number below where 2nd bit is 1, so there will be no change.
Now check 1st
bit of 3rd
number (1). As it is 1, change the rest of the numbers where 1st
bit is 1.
8 : 1000 > changed
4 : 0100 > changed
1 : 0001
No more bit left to consider :)
Now xor the whole remaining array {8 ^ 4 ^ 1} = 13
So 13
is the solution :)
That's pretty much how you solve the problem using Gaussian Elimination :)
Here is my C++ implementation :
#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;
}