题解:Luogu P16258 [DSTOI Round 0] 万分之一的光

· · 题解

题意

有一个序列 a。递归地,定义「过程 \boldsymbol{n}」(其中 n 为正整数)为依次执行如下操作:

  1. 向序列 a 的末尾添加一个 n。
  2. 如果 n > 1,执行「过程 \boldsymbol{n - 1}」。
  3. 如果 n > 2,执行「过程 \boldsymbol{n - 2}」。

给定正整数 n。初始 a = [0]。执行「过程 \boldsymbol{n}」后,设得到的 a = \left[a_1, a_2, \cdots, a_m\right]。容易发现 a_1 = 0,且 m 为 \geq 2 的正整数。

对于 i = 2, 3, \cdots, m,定义 b_i = a_{i - 1} + a_i。若 b_2, b_3, \cdots, b_m 的异或和为 S,试求 S 的值。

本题有 T 组测试数据。

数据范围

## 思路 首先,令 $arr_{n}$ 表示初始时 $a = []$ 的情况下执行「过程 $n$」后的序列 $a$。 如 $arr_{1} = [1]$,$arr_{2} = [2, 1]$,$arr_{3} = [3, 2, 1, 1]$,$arr_{4} = [4, 3, 2, 1, 1, 2, 1]$。 令 $f_{n} = \bigoplus\limits_{i = 2}^{len\left(arr_{n}\right)} (arr_{i - 1} + arr_{i})$,则 $n$ 对应的答案 $S_{n} = (0 + n) \oplus f_{n}$,只要求 $f_{n}$ 即可。 注意到对所有 $n \geq 3$,都有 $arr_{n} = [n] + arr_{n - 1} + arr_{n - 2}$,从而 $arr_{n}$ 的第一个元素为 $n$,且可以归纳证明 $arr_{n}$ 的最后一个元素为 $1$。所以 $$ f_{n} = (n + (n - 1)) \oplus f_{n - 1} \oplus (1 + (n - 2)) \oplus f_{n - 2} $$ 到这里,发现可以 $\mathcal{O}\left(n\right)$ 求出 $f_{1 \sim n}$,所以可以对 $n \leq 10^{5}$ 打表。 打表后发现好像 $f_{n}$ 的量级与 $n \bmod{3}$ 的余数有关。所以可以继续推式子: $$ \begin{aligned} f_{n + 1} &= ((n + 1) + n) \oplus f_{n} \oplus (1 + (n - 1)) \oplus f_{n - 1} \\ &= ((n + 1) + n) \oplus \left((n + (n - 1)) \oplus f_{n - 1} \oplus (1 + (n - 2)) \oplus f_{n - 2}\right) \oplus (1 + (n - 1)) \oplus f_{n - 1} \\ &= (2n + 1) \oplus (2n - 1) \oplus f_{n - 1} \oplus (n - 1) \oplus n \oplus f_{n - 2} \oplus f_{n - 1} \\ &= (2n + 1) \oplus (2n - 1) \oplus (n - 1) \oplus n \oplus f_{n - 2} \end{aligned} $$ 发现确实 $f_{n} = \operatorname{calc}\left(n\right) \times f_{n - 3}$,而 $$ \operatorname{calc}\left(n\right) = (2n - 1) \oplus (2n - 3) \oplus (n - 1) \oplus (n - 2) $$ 从而 $$ f_{n} = \operatorname{calc}\left(n\right) \times \operatorname{calc}\left(n - 3\right) \times \cdots \times \operatorname{calc}\left(((n - 1) \bmod{3}) + 4\right) \times f_{((n - 1) \bmod{3}) + 1} $$ 发现不是很好处理 $\operatorname{calc}$ 的连乘式,于是继续打表。 发现输出结果很有规律: $$ \begin{aligned} \forall x \equiv 0 \pmod{2}, &\operatorname{calc}\left(x\right) = 3 \\ \forall x \equiv 3 \pmod{4}, &\operatorname{calc}\left(x\right) = 5 \\ \forall x \equiv 5 \pmod{8}, &\operatorname{calc}\left(x\right) = 9 \\ \forall x \equiv 9 \pmod{16}, &\operatorname{calc}\left(x\right) = 17 \\ \cdots \end{aligned} $$ 于是猜测有规律:对 $k \geq 1$, $$ \forall x \equiv 2^{k - 1} + 1 \pmod{2^{k}}, \operatorname{calc}\left(x\right) = 2^{k} + 1 $$ 打表可以验证之,所以此结论正确且可以覆盖除 $1$ 以外的所有正整数! 于是现在问题变成了:对每个 $1 \leq k \leq C + \left\lceil\log_{2}{n}\right\rceil$,都要找出有多少个 $((n - 1) \bmod{3}) + 4 \leq x \leq n$ 同时满足 $x \equiv 2^{k - 1} + 1 \pmod{2^{k}}$ 与 $x \equiv n \pmod{3}$。 这是很容易的:直接使用 CRT 合并两个同余关系后,用数论知识算一下即可。需要注意边界条件与 $\pm 1$ 问题。 总时间复杂度 $\mathcal{O}\left(T \times \left(C + \log_{2}{n}\right)\right)$,其中 $C$ 为常数,可以通过。