Project Euler 280
Project Euler 280
题目
Ant and seeds
A laborious ant walks randomly on a \(5\times5\) grid. The walk starts from the central square. At each step, the ant moves to an adjacent square at random, without leaving the grid; thus there are \(2, 3\) or \(4\) possible moves at each step depending on the ant’s position.
At the start of the walk, a seed is placed on each square of the lower row. When the ant isn’t carrying a seed and reaches a square of the lower row containing a seed, it will start to carry the seed. The ant will drop the seed on the first empty square of the upper row it eventually reaches.
What’s the expected number of steps until all seeds have been dropped in the top row?
Give your answer rounded to \(6\) decimal places.
解决方案
令\(M=2,N=5\)。
令坐标为\((x,y)\),其中:
- \(x\in\{0,1,\cdots,N-1\}=\mathbb{Z}_N\)
- \(y\in\mathbb{Z}_N\)
- 底行为\(y=0\),顶行为\(y=N-1\)
接下来用两个\(N\)位掩码(或等价的集合)来描述“尚未完成的列”:
- \(D\subseteq\mathbb{Z}_N\):当前底行仍需触发的列集合(即底行仍“有事要做”的列)。
- \(U\subseteq\mathbb{Z}_N\):当前顶行仍未填满的列集合(即顶行仍为空的列)。
定义期望:\(E_{x,y}(U,D)\)表示从状态\((x,y,U,D)\)出发,直到全部种子都放到顶行所需的期望步数。
初始状态为:\((x,y)=(M,M)\),且\(U=D=\mathbb{Z}_N\)。
显然,若直接把所有状态都铺开,状态数至少达到\(N^2\cdot(2^N+N\cdot 2^{N-1})\),规模较大。为减轻计算负担,当宏状态\((U,D)\)固定时,未知量仅有\(N^2\)个,即\(\{E_{x,y}(U,D)\mid x,y\in\{0,1,2,3,4\}\}.\)因此可将整体系统按宏状态\((U,D)\)进行分块:
- 对于普通格,其方程只会引用同一个\((U,D)\)下的相邻位置期望,因此在这\(N^2\)个未知量内闭合。
- 对于事件格,其方程形如\(E_{x,0}(U,D)=E_{x,N-1}(D\setminus{x},U),\)右端属于另一个宏状态\((U',D')=(D\setminus{x},U)\),从而形成不同块之间的连接。
也就是说,我们对任意一种状态都可以进行一个小规模的线性系统(\(N\times N\)个未知数)的计算,而不必把全部状态一次性纳入系统。
最终,在真实过程里存在两类触发:
- 不携带种子:到达底行\((x,0)\)且该格有种子时,会拾起;
- 携带种子:第一次到达顶行\((x,N-1)\)且该格为空时,会放下。
为避免额外引入“携带/不携带”的布尔状态,我们使用如下等价变换统一事件:
当蚂蚁到达当前底行\((x,0)\)且\(x\in D\)时,立刻触发一次事件,并执行:
- 清掉该列:\(D' = D\setminus{x}\);
- 上下翻转位置:\((x,y)\mapsto(x,N-1-y)\)。此处\(y=0\),所以\((x,0)\mapsto(x,N-1)\);
- 交换上下行任务:\((U,D)\mapsto(D',U)\)。
这样,“拾起后需要去顶行放下”的阶段被翻译成“在翻转后的视角里,仍旧是到达底行触发一次事件”。因此我们只需保留一种事件规则:始终只判断\(y=0\)且\(x\in D\)。
综上,可得到统一的状态转移方程:
\[ E_{x,y}(U,D)= \left\{ \begin{aligned} &0, & & \text{if}\quad U=\varnothing,\\ &E_{x,N-1-y}(D\setminus{x},U), & & \text{else if}\quad y=0\land x\in D,\\ &1+\frac{1}{\deg(x,y)}\sum_{(u,v)\in N(x,y)}E_{u,v}(U,D), & & \text{else}. \end{aligned} \right. \]
其中第一行是终止条件(吸收态):\(U=\varnothing\Rightarrow E_{x,y}(U,D)=0\);第二行表示若当前位置满足\(y=0\)且\(x\in D\),则立即触发事件且不消耗步数;第三行表示否则走一步到相邻格。这里\(\deg(x,y)\)为可走邻居数,\(N(x,y)\)为相邻位置集合。在\(N\times N\)棋盘上,\(\deg(x,y)\)仅有三类取值:
- 角点:\(\deg(x,y)=2\);
- 边但非角:\(\deg(x,y)=3\);
- 内部:\(\deg(x,y)=4\)。
最终所求答案即为\[E_{M,M}(\mathbb{Z}_N,\mathbb{Z}_N).\]
代码
1 | from functools import cache |