题解 洛谷 U327217 寻找千泷の小翼龙
原题(本题由该题数据加强而来):
USACO Training 6.1.1 Postal Vans
Tiring of their idyllic fields, the cows have moved to a new suburb. The suburb is a rectangular grid of streets with a post office at its Northwest corner. It has four avenues running East-West and $n(1\le n\le 10^{18})$ streets running North-South.
For example, the following diagram shows such a suburb with $n=5$ streets, with the avenues depicted as horizontal lines, and the post office as a dark blob at the top-left corner:

Each day the postal van leaves the post office, drives around the suburb and returns to the post office, passing exactly once through every intersection (including those on borders or corners). The executives from the post company want to know how many distinct routes can be established for the postal van (of course, the route direction is significant in this count).
For example, the following diagrams show two such routes for the above suburb:

As another example, the following diagrams show all the four possible routes for a suburb with $n=3$ streets:

Write a program that will determine the number of such distinct routes given the number of streets.
INPUT FORMAT
Line 1: Two integers, n, p
SAMPLE INPUT:
1 | 4 32767 |
OUTPUT FORMAT
Line 1: A single integer that tells how many possible distinct routes corresponding to the number of streets given in the input, mod p;
SAMPLE OUTPUT:
1 | 12 |
简要题意:
给定一个$4\times n$的格子(按照格点计数),从左上角出发沿格子遍历所有格点后再返回起点,要求每个点只遍历一次,计算合法方案的总数 $mod$ $p$ 的值
策略分析:
看到方案数,我们合理地想到了动态规划,而看到数据范围和动态规划,我们合理地想到了矩阵加速。设 $f_i$ 为前 $i$ 列中第 $i$ 列中总的方案数。大家小时候应该都玩过拼管子吧,就那种各种各样形状的管子可以组合成不同的形状,那么本题就是要用类似的方法。
到达南北方向 $1,2$ 路口的方案只有 $2$ 种,我们将管子如下摆放:


到达南北方向 $1,4$ 路口方案有 $7$ 种,但最后两种等价算作一种:








由此我们可以推出状态转移方程,即:
$$f_i=2f_{i-1}+2f_{i-2}-2f_{i-3}+f_{i-4}$$
对于这种方法和递推方程正确性的证明参见阿蒋大佬的blog
得到了状态转移方程我们就可以得到转移矩阵 $M$ 了,
$$M=\begin{vmatrix}
2& 2& -2& 1\
1& 0& 0& 0\
0& 1& 0& 0\
0& 0& 1& 0
\end{vmatrix}$$
我们充分发扬人类智慧,通过大脑和手求得 $f_1=0,f_2=2,f_3=4,f_4=12$
剩余部分显然没有难度了,直接矩阵加速就可以了,于是我们做完了,下面是 $AC$ 代码
1 |
|
说些什么吧!