Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P4301 [CQOI2013] 新Nim游戏

P4301 [CQOI2013] 新Nim游戏

考虑 Nim 游戏胜利的条件,先手需要在任意时刻保持留下一个异或和为 $0$ 的局面,因此,在先手第一回合取后,不论后手拿走哪些数,都不能使得异或和为 $0$ 。使得拿走的总数最小,也就是留下的最多,那么就是留下一个线性基。为了使得留下的最多,即线性基和最大,那么排序,贪心先插入大的。如果不能插入,则说明插入后异或和为 $0$ ,那么先手需要取走。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long LL;
template <class Type>
void read(Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 3) + (x << 1) + c - '0';
flag && (x = ~x + 1);
}
template <class Type>
void write(Type x)
{
x < 0 && (putchar('-'), x = ~x + 1);
x > 9 && (write(x / 10), 0);
putchar(x % 10 + '0');
}
const int N = 110, M = 30;
int n, w[N], bs[M];
bool insert (int x)
{
for (int i = M - 1; ~i; i--)
if (x >> i & 1)
{
if (!bs[i])
return bs[i] = x, false;
x ^= bs[i];
}
return true;
}
int main ()
{
read(n);
for (int i = 0; i < n; i++)
read(w[i]);
sort(w, w + n);
LL res = 0;
for (int i = n - 1; ~i; i--)
insert(w[i]) && (res += w[i]);
write(res);
return 0;
}