P6154 游走
题意:
给定一个有向无环图,在图上游走,每次选定一条路径,起点和终点可以相同
选择每条路径的概率相同,求一条路径的期望长度
思路:
期望
E
(
X
)
=
∑
X
i
×
P
(
X
i
)
E(X)=\sum X_i\times P(X_i)
E(X)=∑Xi×P(Xi)
每条路径出现的概率相同,设总路径和为
l
e
n
g
t
h
length
length,总路径数为
n
u
m
num
num
那么期望就是
l
e
n
g
t
h
n
u
m
\frac{length}{num}
numlength
设
s
u
m
[
x
]
,
c
n
t
[
x
]
sum[x],cnt[x]
sum[x],cnt[x] 分别表示以
x
x
x 结尾的总路径长度和总路径数
路径条数这么来计:
以
x
x
x 结尾的路径条数为
n
u
m
[
x
]
num[x]
num[x],设
x
x
x 的后继节点
t
o
to
to,把
t
o
to
to 加入以
x
x
x 结尾的路径的末尾,那么以
t
o
to
to 结尾的路径数将增加
n
u
m
[
x
]
num[x]
num[x] ,拓扑排序时转移即可
总路径和:
分析与上同理,
x
x
x 转移到
t
o
to
to 时,之前的每条路径长度都会
+
1
+1
+1,对总路径长度和的贡献为
n
u
m
[
x
]
num[x]
num[x],然后加上总路径之前的长度和
s
u
m
[
x
]
sum[x]
sum[x], 即得到以
t
o
to
to 结尾的路径长度和
code:
#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define ld long double
#define all(x) x.begin(), x.end()
#define mem(x, d) memset(x, d, sizeof(x))
#define eps 1e-6
using namespace std;
const int maxn = 2e6 + 9;
const int mod = 998244353;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
ll n, m;
vector <int> e[maxn];
int in[maxn], sum[maxn], num[maxn];
ll q_pow(ll a, ll b){
ll ans = 1;while(b){
if(b & 1) ans = ans * a % mod;b >>= 1;a = a * a % mod;
}return ans;
}
void topsort(){
queue <int> q;
for(int i = 1; i <= n; ++i)
{
num[i] = 1;//每个点都可以看成一条路径
if(!in[i]) q.push(i);
}
while(!q.empty()){
int x = q.front();q.pop();
for(int to : e[x]){
in[to]--;
if(!in[to]) q.push(to);
(num[to] += num[x]) %= mod;
(sum[to] += (sum[x] + num[x]) % mod) %= mod;
}
}
}
void work()
{
cin >> n >> m;
for(int i = 1; i <= m; ++i){
int x, y;cin >> x >> y;e[x].push_back(y);in[y]++;
}
topsort();
ll ans = 0, cnt = 0;
for(int i = 1; i <= n; ++i) (ans += sum[i]) %= mod, (cnt += num[i]) %= mod;
cout << ans * q_pow(cnt, mod - 2) % mod;
}
int main()
{
ios::sync_with_stdio(0);
// int TT;cin>>TT;while(TT--)
work();
return 0;
}