带状矩阵消元模板题。
设 表示从 走到圆外的期望时间。
若 有 。
否则有 。
注意到状态之间互相依赖,显然不能直接转移。于是不难想到将转移式当作方程解,使用高斯消元求解可以做到 。
但是 过不去。
我们不妨将 不为 的 进行标号。
观察转移式发现 之间编号差不超过 。
那么我们的矩阵其实就是带宽不超过 的带状矩阵。使用带状矩阵一般方法求解,容易做到 。
常数略大,但是 cf 测评机随便跑。
Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
// #define int ll
const int mod = 1e9 + 7;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, -1, 0, 1};
int R, a1, a2, a3, a4, tot = 0, res[7846];
int a[7846][7846], p[4];
int X[7846], Y[7846], ID[107][107];
inline int ksm(int a, int b, int mod)
{
int res = 1;
while (b)
{
if (b & 1)
res = 1ll * res * a % mod;
a = 1ll * a * a % mod;
b >>= 1;
}
return res;
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> R >> a1 >> a2 >> a3 >> a4;
int x = ksm(a1 + a2 + a3 + a4, mod - 2, mod);
p[0] = 1ll * a1 * x % mod;
p[1] = 1ll * a2 * x % mod;
p[2] = 1ll * a3 * x % mod;
p[3] = 1ll * a4 * x % mod;
for (int i = -R; i <= R; i++)
for (int j = -R; j <= R; j++)
if (i * i + j * j <= R * R)
ID[i + R][j + R] = ++tot, X[tot] = i, Y[tot] = j;
for (int i = 1; i <= tot; i++)
{
int x = X[i], y = Y[i];
a[i][i] = 1;
a[i][0] = 1;
for (int j = 0; j < 4; j++)
{
int nx = x + dx[j];
int ny = y + dy[j];
if (nx * nx + ny * ny > R * R)
continue;
a[i][ID[nx + R][ny + R]] = mod - p[j];
}
}
for (int i = 1; i <= tot; i++)
{
for (int j = i + 1; j <= min(i + 2 * R, tot); j++)
{
x = 1ll * a[j][i] * ksm(a[i][i], mod - 2, mod) % mod;
for (int k = max(i, j - 2 * R); k <= min(tot, j + 2 * R); k++)
a[j][k] = ((a[j][k] - 1ll * x * a[i][k] % mod) % mod + mod) % mod;
a[j][0] = ((a[j][0] - 1ll * x * a[i][0] % mod) % mod + mod) % mod;
}
}
for (int i = tot; i >= 1; i--)
{
for (int j = i + 1; j <= tot; j++)
a[i][0] = ((a[i][0] - 1ll * a[i][j] * res[j] % mod) % mod + mod) % mod;
res[i] = 1ll * a[i][0] * ksm(a[i][i], mod - 2, mod) % mod;
}
cout << res[ID[R][R]];
}