luogu T202676 网格游走
Description–
有一个 3 × 3 3\times 3 3×3 的网格。最开始每一个格子上都有一个机器人。
在每一秒内,每一个机器人可能往上下左右四个方向走一步,或者停留在原地不动。也就是如果这一秒一个机器人在 ( x , y ) (x,y) (x,y),那么下一秒这个机器人可能会在 ( x + 1 , y ) , ( x − 1 , y ) , ( x , y + 1 ) , ( x , y − 1 ) , ( x , y ) (x+1,y),(x-1,y),(x,y+1),(x,y-1),(x,y) (x+1,y),(x−1,y),(x,y+1),(x,y−1),(x,y) 中。当然,前提是不能越出这个 3 × 3 3\times 3 3×3 的网格。
求在
n
n
n 秒后,有多少行动方案(对
1
0
9
+
7
10^9+7
109+7 取模)使得每一个格子恰好有一个机器人。
两种方案不同当且仅当在某一秒,一个机器人的行动不同。
注意,两个机器人可以同时在一个格子上。
Input–
第一行一个正整数 n n n。
Output–
输出一个整数,表示方案数对 1 0 9 + 7 10^9+7 109+7 取模后的值。
Sample Input–
23333
Sample Output–
347338733
说明–
解题思路–
预处理每个点n次之后到达某点的方案数
然后从每个点出发统计答案就行了
快速幂记得开 l o n g l o n g longlong longlong(苦涩
代码–
#include <iostream>
#include <cstring>
#include <cstdio>
#define ll long long
using namespace std;
const ll M = 1e9 + 7;
const int fx[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
ll n, ans, p[15], pd[15];
struct hll
{
ll a[15][15];
}x, y;
hll operator *(hll a, hll b) //矩阵乘法
{
hll an;
memset(an.a, 0, sizeof(an.a));
for (int i = 1; i <= 9; ++i)
for (int j = 1; j <= 9; ++j)
for (int l = 1; l <= 9; ++l)
an.a[i][j] = (an.a[i][j] + a.a[i][l] * b.a[l][j] % M) % M;
return an;
}
void dfs(int lev, ll an)
{
if (lev > 9)
{
ans = (ans + an) % M;
return ;
}
for (int i = 1; i <= 9; ++i)
if (!pd[i])
{
pd[i] = 1, p[lev] = i;
dfs(lev + 1, an * y.a[lev][i] % M), pd[i] = 0;
}
}
hll power(ll b) //快速幂
{
hll an = x;
b--;
for (; b; b >>= 1)
{
if (b & 1) an = an * x;
x = x * x;
}
return an;
}
int main()
{
scanf("%lld", &n);
for (int i = 1; i <= 3; ++i)
for (int j = 1; j <= 3; ++j)
{
int u = (i - 1) * 3 + j;
for (int l = 0; l < 4; ++l)
{
int xx = i + fx[l][0];
int yy = j + fx[l][1];
if (xx < 4 && xx > 0 && yy < 4 && yy > 0)
x.a[u][(xx - 1) * 3 + yy] = 1;
}
x.a[u][u] = 1;
}
for (int i = 1; i <= 9; ++i) y.a[i][i] = 1; //可省略
y = y * power(n);
dfs(1, 1);
printf("%lld",ans);
return 0;
}