275. To xor or not to xor
time limit per test: 0.5 sec.
memory limit per test: 65536 KB
input: 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
Output
14
这个题目可以将每个数分解成64位来看待,于是我们可以从高位向低位扫描,尽可能让当前这位为1,而判断当前这位是否可能为1可以借助高斯消元。
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define MAXN 110
#define MAXM 70
using namespace std;
long long a[MAXN];
int N, mat[MAXM][MAXN], code[MAXM][MAXN], ans[MAXM];
void decode(int i)
{
int j;
long long x = a[i];
for(j = 63; j >= 0; j --)
code[j][i] = x & 1, x >>= 1;
}
void init()
{
int i;
for(i = 0; i < N; i ++)
{
scanf("%I64d", &a[i]);
decode(i);
}
}
int gauss(int n)
{
int i, j, k, x, y;
for(i = j = 0; i <= n && j < N; i ++, j ++)
{
if(mat[i][j] == 0)
{
for(x = i + 1; x <= n; x ++)
if(mat[x][j])
{
for(y = j; y <= N; y ++)
swap(mat[i][y], mat[x][y]);
break;
}
if(x > n)
{
-- i;
continue ;
}
}
for(x = i + 1; x <= n; x ++)
if(mat[x][j])
{
for(y = j; y <= N; y ++)
mat[x][y] ^= mat[i][y];
}
}
for(k = i; k <= n; k ++)
if(mat[k][N])
return 0;
return 1;
}
void solve()
{
int i, j, k;
long long res = 0;
for(i = 0; i < 64; i ++)
{
ans[i] = 1;
for(j = 0; j <= i; j ++)
{
for(k = 0; k < N; k ++)
mat[j][k] = code[j][k];
mat[j][N] = ans[j];
}
if(!gauss(i))
ans[i] = 0;
}
for(i = 0; i < 64; i ++)
res = (res << 1) | ans[i];
printf("%I64d\n", res);
}
int main()
{
while(scanf("%d", &N) == 1)
{
init();
solve();
}
return 0;
}