ICPC南京网络赛D.robot

题意:

给定一颗有向无环图,要求从1走到n所需能量的期望,在走到一个点的时候,有相等概率走到随机一条边,花费一天时间。第i天花费i的能量

代码
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
#include <iostream>
#include <queue>
#include <cstdio>
#include <vector>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
vector<int> g[N];
double dp1[N], dp2[N];
int n, m, T;
void init()
{
for (int i = 1; i <= n; i++)
dp1[i] = dp2[i] = 0;
for (int i = 1; i <= n; i++)
g[i].clear();
}
void dfs(int x)
{
if (g[x].size() == 0)
{
dp1[x] = 0;
dp2[x] = 0;
return;
}
if (dp1[x])
return;
double sum1 = 0;
double sum2 = 0;
for (int i = 0; i < g[x].size(); i++)
{
dfs(g[x][i]);
sum1 += dp1[g[x][i]];
sum2 += dp2[g[x][i]];
}
dp1[x] = (sum1 + 1 + g[x].size()) / (g[x].size() * 1.0);
dp2[x] = (sum2 + (g[x].size() + 1) * dp1[x]) / (g[x].size() * 1.0);
}
int main()
{
scanf("%d", &T);
while (T--)
{
scanf("%d%d", &n, &m);
init();
for (int i = 1; i <= m; i++)
{
int u, v;
scanf("%d%d", &u, &v);
g[u].push_back(v);
}
dfs(1);
printf("%.2lf\n", dp2[1]);
}
}