题解:P6639 「JYLOI Round 1」让

· · 题解

题意简述

定义一种游戏如下:给定常数 R。初始有 k 堆石子,第 i 堆有 p_i 个石子。双方轮流操作,每次可以选一堆有 x 个石子的堆取 y 个且满足 x + y \le R。

要求支持动态修改 R。每次询问给出 n 对数 (l_i,r_i) 表示有 l_i,l_i+1,\dots,r_i 这 r_i - l_i + 1 堆石子,问先手是否有必胜策略。

思路

考虑一堆的 SG 函数 SG(x),根据定义有:

SG(x) = \operatorname{mex}_{1 \le i \le x,i + x \le R} SG(x-i)

设 S_i = \{i - j | 1 \le j \le i,i + j \le R\} = \{j|\max\{0,2i-R\} \le j < i\}。

首先,我们先证明,\forall i \in [0,\lfloor \frac{R}{2} \rfloor],SG(i) = i。

::::info[证明]{open}

假设 $SG(i) = i$ 对 $[0,n]$ 成立,则根据 $n + 1 \le \lfloor \frac{R}{2} \rfloor$ 有 $S_{n+1} = [0,n]$。根据公式: $$\begin{aligned} SG(n+1) &= \operatorname{mex}_{0 \le i \le n} i \\ &= n + 1 \end{aligned}$$ 根据数学归纳法得证。 :::: 设 $z_i$ 表示从小到大第 $i$ 个数满足 $SG(z_i) = 0$。显然有 $z_1 = 0$。 由于 $R - (\lfloor \frac{R}{2} \rfloor + 1) > \lfloor \frac{R}{2} \rfloor$,故 $SG(\lfloor \frac{R}{2} \rfloor + 1) = 0$,$z_2 = \lfloor \frac{R}{2} \rfloor + 1$。 再往后,考虑 $S_x$ 和 $S_{x+1}$ 的区别。发现只有最前面少了两个数,最后面多了一个数。如果少的数还没有包含 $0$,由于少的数较大,不会对 $\operatorname{mex}$ 产生影响,故最后多的数会使答案加 $1$。 如果少的数包含 $0$,后面的部分依次递增,根据 $\operatorname{mex}$ 的定义有 $SG(x+1) = 0$。此时 $z_i = x+1$ 满足 $SG(2x - R) = 0$ 或 $SG(2x - R + 1) = 0$。我们就得到了递推式 $z_i = \lfloor \frac {z_{i-1}+R}{2} \rfloor + 1$。 考虑单个区间,我们要求 $\operatorname{xor}_{i \in [l,r]} SG(i) = (\operatorname{xor}_{i \in [0,l-1]} SG(i)) \operatorname{xor} (\operatorname{xor}_{i \in [0,r]} SG(i))$。由于 SG 函数每一段都是 $0 \sim m$ 的形式,这一段异或起来就是 $\operatorname{xor}_{i \in [0,m]}i$。把所有段异或起来就得到了最终答案。 现在只需要考虑 $\operatorname{xor}_{i \in [0,x]}i$。由于 $(4x) \operatorname{xor} (4x+1) \operatorname{xor} (4x+2) \operatorname{xor} (4x+3) = 0$,考虑以 $4$ 为循环计算。故有: $$\operatorname{xor}_{i \in [0,x]}i = \begin{cases} x & x \bmod 4 = 0 \\ (x-1) \operatorname{xor} x = 1 & x \bmod 4 = 1 \\ 1 \operatorname{xor} x & x \bmod 4 = 2 \\ 0 & x \bmod 4 = 3\end{cases}$$ 最后把所有的区间的 SG 异或值异或起来得到最终的 SG 值,如果不是 $0$ 先手胜,否则后手胜。 因为 $z_i$ 能比 $z_{i-1}$ 逼近 $R$ 一半,故使用递推式枚举 $z_i$ 的复杂度为 $O(\log R)$。区间异或和可以使用上述公式 $O(1)$ 计算。总时间复杂度是 $O(\sum n \log R)$,空间复杂度 $O(1)$。 如果预计算所有 $z_i$ 应该可以做到时间复杂度 $O(\sum \log R + \sum n \log \log R)$,空间复杂度 $O(\log R)$。~~不过我懒。~~ ## 代码 实现起来并不难。 ```cpp #include <bits/stdc++.h> using namespace std; using ll = long long; int t, n; string op; ll r, s, e, ans; ll xorsum(ll x) { // 异或前缀和 switch (x & 3) { case 0: return x; case 1: return 1; case 2: return x | 1; case 3: return 0; } } inline ll sumSG(ll n) { // SG 函数异或和 ll res = 0, cur = 0, nxt; // 答案,z_i,z_{i+1} while (cur <= n) { nxt = ((cur + r) >> 1) + 1; if (nxt > n) { // 不完整的段 res ^= xorsum(n - cur); break; } res ^= xorsum(nxt - cur - 1); // 完整段 cur = nxt; } return res; } signed main() { cin.tie(nullptr); cout.tie(nullptr); ios::sync_with_stdio(false); cin >> t; while (t--) { cin >> op; if (op == "change") cin >> r; else if (op == "query") { cin >> n; ans = 0; while (n--) { cin >> s >> e; ans ^= (sumSG(e) ^ sumSG(s - 1)); // 全部异或得到最终 SG 值。 } cout << (ans != 0); } } } ```