题目大意:在一个DAG上,保证所有的点都在 1 -> n的路径上,机器人在 i 点时可以等概率的选择沿有向边走到相邻点或呆在原点,每过一天机器人花费的能量是已经过去的天数之和,问 从 1号点走到号点的花费能量的期望。
(题都读错了,读成了一般有向图)
做法:显然可以从 n 号点倒推推出 从i 号点走到号点的期望天数,设为dp[i]。转移方程:
d
p
[
i
]
=
(
∑
<
i
,
j
>
∈
E
d
p
[
j
]
d
[
i
]
+
1
)
+
d
p
[
i
]
d
[
i
]
+
1
+
1
dp[i] = (\sum_{<i,j> \in E}\frac{dp[j]}{d[i] +1}) + \frac{dp[i]}{d[i] + 1} + 1
dp[i]=(<i,j>∈E∑d[i]+1dp[j])+d[i]+1dp[i]+1
设 cost[i] :从 i 点走到 n号点的期望花费。转移方程:
c
o
s
t
[
i
]
=
(
∑
<
i
,
j
>
∈
E
c
o
s
t
[
j
]
+
d
p
[
i
]
d
[
i
]
+
1
)
+
c
o
s
t
[
i
]
d
[
i
]
+
1
+
d
p
[
i
]
d
[
i
]
+
1
cost[i] = (\sum_{<i,j> \in E}\frac{cost[j] +dp[i]}{d[i] +1}) +\frac{cost[i]}{d[i] + 1} + \frac{dp[i]}{d[i] +1}
cost[i]=(<i,j>∈E∑d[i]+1cost[j]+dp[i])+d[i]+1cost[i]+d[i]+1dp[i]
cost[i]的转移方程什么意思:假设已经计算出cost[j],显然从 i 号点走到 j会增加从j走到 n 的花费,具体增加多少:从 i -> j 要花费一天,之后j的起步花费都会多1,从 i 到 n 要几天总花费就会增加多少。
#include<bits/stdc++.h>
using namespace std;
const int maxn = 3e6 + 10;
vector<int> g[maxn],h[maxn];
int t,n,m;
int d[maxn],d2[maxn];
double dp[maxn],cost[maxn];
void tpsort() {
queue<int> q;
q.push(n);
while(!q.empty()) {
int top = q.front();
q.pop();
dp[top] = 0;
int p = (int)g[top].size() + 1;
if(p > 1) {
for(auto it : g[top])
dp[top] += 1.0 * dp[it] / p;
dp[top] += 1;
dp[top] *= 1.0 * p / (p - 1);
}
for(auto it : h[top]) {
d[it]--;
if(!d[it]) q.push(it);
}
}
}
void tpsort2() {
queue<int> q;
q.push(n);
while(!q.empty()) {
int top = q.front();
q.pop();
cost[top] = 0;
int p = (int)g[top].size() + 1;
if(p > 1) {
for(auto it : g[top])
cost[top] += 1.0 * (cost[it] + dp[top]) / p;
cost[top] += dp[top] / p;
cost[top] *= 1.0 * p / (p - 1);
}
for(auto it : h[top]) {
d2[it]--;
if(!d2[it]) q.push(it);
}
}
printf("%.2lf\n",cost[1]);
}
int main() {
scanf("%d",&t);
while(t--) {
scanf("%d%d",&n,&m);
fill(d,d + n + 1,0);
fill(d2,d2 + n + 1,0);
for(int i = 1; i <= m; i++) {
int u,v;scanf("%d%d",&u,&v);
g[u].push_back(v);
h[v].push_back(u);
d[u]++;d2[u]++;
}
cost[n] = dp[n] = 0;
tpsort();
tpsort2();
for(int i = 1; i <= n; i++)
h[i].clear(),g[i].clear();
}
return 0;
}