教學上機考第四題題解
不要笑←不要笑↓不要笑→
題目
兎田ぺこら的笑聲有各式各樣的方向(共8個方向),但是總有個笑聲的規律,他想知道自己在特定長度的笑聲有幾種組法。
現在ぺこら想找你寫一隻程式,請你計算在時長為n的時候有幾種笑法。考慮到答案可能很大,故請將結果模1e9+7輸出。
笑聲規律:↗ +↘總共的數量為偶數,↑和↓的數量總和為奇數個
笑聲有八種方向
↗ +↘為偶數,↑+↓為奇數
求滿足條件且排列長度為n的方法數
簡單來說
subtask1-2
DP
1\le N\le 1e6
DP
定義狀態
f(長度,↗ +↘為偶數,↑+↓為奇數)
初始狀態
f(1,1,0)=4\\
f(1,1,1)=2\\
f(1,0,0)=2\\
f(1,0,1)=0\\
DP
導出轉移
f(↗ +↘為偶數,↑+↓為奇數)
f(1,1)=
f(0,1)=4f(0,1)+2f(1,0)+2f(0,0)
f(1,0)=
f(0,0)=4f(0,0)+2f(1,0)+2
f(0,1)
4f(1,1)
+2f(1,0)
+2f(0,1)
4f(1,0)
+2f(1,1)
+2f(0,0)
n
n-1
時間複雜度\Omicron(N)
subtask1-2
1\le N\le 1e6
50分
subtask3
1\le N\le 1e18
快速冪
x^n=x*x*x...\\時間複雜度\Omicron(n)
n為偶數
x^n=x^{\smash{n/2}}*x^{\smash{n/2}}
n為奇數
x^n=x*x^{\smash{n-1/2}}*x^{\smash{n-1/2}}
時間複雜度\Omicron(\log n)
矩陣乘法
\begin{bmatrix}
f(n,1,1)\\
f(n,1,0) \\
f(n,0,1)\\
f(n,0,0)\\
\end{bmatrix}=
\begin{bmatrix}
4 & 2 & 2 & 0 \\
2 & 4 & 0 & 2 \\
2&0&4&2\\
0&2&2&4\\
\end{bmatrix}
\begin{bmatrix}
f(n-1,1,1)\\
f(n-1,1,0) \\
f(n-1,0,1)\\
f(n-1,0,0)\\
\end{bmatrix}\\
改寫遞迴式
矩陣快速冪
\begin{bmatrix}
f(n,1,1)\\
f(n,1,0) \\
f(n,0,1)\\
f(n,0,0)\\
\end{bmatrix}=\begin{bmatrix}
4 & 2 & 2 & 0 \\
2 & 4 & 0 & 2 \\
2&0&4&2\\
0&2&2&4\\
\end{bmatrix}^{\smash{n-1}}
\begin{bmatrix}
2\\
4\\
2\\
0\\
\end{bmatrix}
時間複雜度\Omicron(\log
N)AC
教學上機考第四題題解
By chenyanjun
教學上機考第四題題解
- 49