Time Limit:250MS | Memory Limit:65536KB | 64bit IO Format:%I64d & %I64u |
Description
275. To xor or not to xor
time limit per test: 0.25 sec.
memory limit per test: 65536 KB
memory limit per test: 65536 KB
input: standard
output: standard
output: standard
The sequence of non-negative integers A1, A2, ..., AN is given. You are to find some subsequence Ai
1, Ai
2, ..., Ai
k (1 <= i
1 < i
2 < ... < i
k <= N) such, that Ai
1 XOR Ai
2 XOR ... XOR Ai
k has a maximum value.
Input
The first line of the input file contains the integer number N (1 <= N <= 100). The second line contains the sequence A1, A2, ..., AN (0 <= Ai <= 10^18).
Output
Write to the output file a single integer number -- the maximum possible value of Ai
1 XOR Ai
2 XOR ... XOR Ai
k.
Sample test(s)
Input
3
11 9 5
11 9 5
Output
14
题意:给你n个数,可以选择任意个数异或,但是要使得最后的异或值最大。
我们把每个数用二进制表示,要使得最后的异或值最大,就是要让高位尽量为1,高位能不能为1就必须用高斯消元判断了。
1. 根据数的二进制表示,建立方程组的矩阵,结果那列置为1。
2. 从下往上高斯消元(高位放下面),如果该行有未被控制的变元,则该行的结果一定为1,且该变元控制该行。
3. 从该行往上依次消掉(异或)该变元。
4. 如果该行没有可以用来控制的变元,如果最后一列是0,则该行结果也为1,否则该行结果为0。这里能抱着已用来控制的变元的系数全是0,因为在第3步时就消掉该行以上此列的0了,后面0与0以后还是0。所以如果最后一列是0, 即该行方程也可以成立,故结果为1。
建立方程:
a11x1+a21x2……=d[1]
a12x1+a22x2……=d[2]
……
因为消元的时候前面的方程对后面是没有影响的,所以是对的#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
const int maxn=110;
const int M=63;
typedef long long LL;
int a[maxn][maxn];
LL xp[maxn];
int N;
void Gauss()
{
LL ans=0;
for(int i=0;i<M;i++)
{
int x=-1;
for(int j=0;j<N;j++)
if(a[i][j])
{
x=j;
break;
}
if(x==-1&&a[i][N]==0)
ans+=xp[62-i];
else if(x!=-1)
{
ans+=xp[62-i];
for(int k=i+1;k<M;k++)
{
if(a[k][x])
for(int j=0;j<=N;j++)
a[k][j]^=a[i][j];
}
}
}
cout<<ans<<endl;
}
int main()
{
xp[0]=1;
for(int i=1;i<M;i++)xp[i]=xp[i-1]*2;
while(scanf("%d",&N)!=EOF)
{
LL x;
for(int i=0;i<N;i++)
{
cin>>x;
for(int j=0;j<M;j++)
if(x&xp[j])a[62-j][i]=1;
else a[62-j][i]=0;
}
for(int i=0;i<M;i++)a[i][N]=1;
Gauss();
}
return 0;
}