JZOJ 6385.B

考虑一般图上的随机游走问题,易列得方程 fu=1degu(u,v)Efvf_u = \frac1{deg_u}\sum\limits_{(u,v) \in E} f_v
复杂度 O(n3)O(n^3)

但是这一题运用了系数的一个特点:若从下往上(即从 nn11)消元,则消到 pp 时,只有 p,fap,fafapp,fa_p,fa_{fa_p} 的方程中 fpf_p 的系数不为 11
故总共需要消元的方程是 O(n)O(n) 级别的。
复杂度 O(n2)O(n^2)

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <cstdio>
using namespace std;
const int N = 2e3;
const int mod = 998244353;
inline int fpow(int a,int b)
{
int ret = 1;
for(;b;b >>= 1)
(b & 1) && (ret = (long long)ret * a % mod),a = (long long)a * a % mod;
return ret;
}
int n,fa[N + 5],deg[N + 5];
int a[N + 5][N + 5],f[N + 5];
int to[(N << 2) + 5],pre[(N << 2) + 5],first[N + 5];
inline void add(int u,int v)
{
static int tot = 0;
to[++tot] = v,pre[tot] = first[u],first[u] = tot;
}
int main()
{
freopen("b.in","r",stdin),freopen("b.out","w",stdout);
scanf("%d",&n);
for(register int i = 2;i <= n;++i)
scanf("%d",fa + i),add(fa[i],i),add(i,fa[i]),++deg[fa[i]],++deg[i],fa[fa[i]] && (add(fa[fa[i]],i),add(i,fa[fa[i]]),++deg[fa[fa[i]]],++deg[i]);
a[1][1] = 1;
for(register int i = 2,inv;i <= n;++i)
{
inv = fpow(deg[i],mod - 2),a[i][0] = a[i][i] = 1;
for(register int j = first[i];j;j = pre[j])
a[i][to[j]] = mod - inv;
}
for(register int i = n,inv;i;--i)
{
if(fa[i])
{
inv = (long long)a[fa[i]][i] * fpow(a[i][i],mod - 2) % mod;
for(register int j = 0;j <= n;++j)
a[fa[i]][j] = (a[fa[i]][j] - (long long)a[i][j] * inv % mod + mod) % mod;
}
if(fa[fa[i]])
{
inv = (long long)a[fa[fa[i]]][i] * fpow(a[i][i],mod - 2) % mod;
for(register int j = 0;j <= n;++j)
a[fa[fa[i]]][j] = (a[fa[fa[i]]][j] - (long long)a[i][j] * inv % mod + mod) % mod;
}
}
for(register int i = 1;i <= n;++i)
for(register int j = first[i],inv;j;j = pre[j])
if((to[j] ^ fa[i]) && (to[j] ^ fa[fa[i]]))
{
inv = (long long)a[to[j]][i] * fpow(a[i][i],mod - 2) % mod;
for(register int k = 0;k <= n;++k)
a[to[j]][k] = (a[to[j]][k] - (long long)a[i][k] * inv % mod + mod) % mod;
}
for(register int i = 1;i <= n;++i)
printf("%d\n",(long long)a[i][0] * fpow(a[i][i],mod - 2) % mod);
}