链接:https://ac.nowcoder.com/acm/problem/21298
来源:牛客网
题号:NC21298
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 524288K,其他语言1048576K
64bit IO Format: %lld
题目描述
给你一个n个元素的数组x
你需要找到一个数组a, 0 ≤ a[i] ≤ x[i]
使得a[0] xor a[1]... xor a[n-1]最大
输出这个最大值
输入描述:
第一行输入一个整数n (1 ≤ n ≤ 50)
第二行输入n个整数 xi (0 ≤ xi ≤ 1e9)
输出描述:
输出一个整数
示例1
输入
3
2 2 2
输出
3
思路
贪心:
考虑异或不会超过最高位,那么将数组排序,从最大的数(含有最高位)开始异或,设当前异或数为\(curr\),对于每一个给定的\(x_i\),我们从\(x_i\)的最高bit位开始,如果当前\(curr\)在该bit位为1,那么可以保证\(x\)该bit位为1满足\(x < x_i\), 如果当前\(curr\)在该bit位为0,那么我们判断加上当前bit位是否满足小于\(x_i\), 这种贪心的策略可以保证我们得到的异或数满足\(x < x_i\),并且为最大的异或数。
Code
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long LL;
vector<int> a;
LL cal(int x, int val) {
LL ans = 0;
int pos;
for (pos = 31; pos >= 0 && !(val>>pos&1); pos --);
if (pos < 0) return x;
for (; pos >= 0; pos --) {
if (!(val>>pos&1)) {
if (ans + (1<<pos) > x) continue;
ans += (1<<pos);
}
}
return ans;
}
int main() {
int n, curr = 0; cin >> n;
a.resize(n + 1);
for (int i = 1; i <= n; i ++) cin >> a[i];
sort(a.begin() + 1, a.end(), greater<int>());
for (int i = 1; i <= n; i ++) {
curr ^= cal(a[i], curr);
}
cout << curr;
}