3036: 绿豆蛙的归宿

Description

随着新版百度空间的下线,Blog宠物绿豆蛙完成了它的使命,去寻找它新的归宿。

给出一个有向无环的连通图,起点为1终点为N,每条边都有一个长度。绿豆蛙从起点出发,走向终点。
到达每一个顶点时,如果有K条离开该点的道路,绿豆蛙可以选择任意一条道路离开该点,并且走向每条路的概率为 1/K 。
现在绿豆蛙想知道,从起点走到终点的所经过的路径总长度期望是多少?

Input

第一行: 两个整数 N M,代表图中有N个点、M条边
第二行到第 1+M 行: 每行3个整数 a b c,代表从a到b有一条长度为c的有向边

Output


从起点到终点路径总长度的期望值,四舍五入保留两位小数。

Sample Input

4 4

1 2 1

1 3 2

2 3 3

3 4 4

Sample Output

7.00
HINT

对于100%的数据 N<=100000,M<=2*N

拓扑排序然后算期望长度

 1 const
 2     maxn=100100;
 3     maxm=maxn*2;
 4 var
 5     first,d,c:array[0..maxn]of longint;
 6     f,dis:array[0..maxn]of double;
 7     next,last,len:array[0..maxm]of longint;
 8     n,m,tot:longint;
 9 
10 procedure insert(x,y,z:longint);
11 begin
12     inc(tot);
13     last[tot]:=y;
14     next[tot]:=first[x];
15     first[x]:=tot;
16     len[tot]:=z;
17     inc(d[y]);
18     inc(c[x]);
19 end;
20 
21 procedure init;
22 var
23     i,x,y,z:longint;
24 begin
25     read(n,m);
26     for i:=1 to m do
27       begin
28         read(x,y,z);
29         insert(x,y,z);
30       end;
31 end;
32 
33 var
34     q:array[0..maxn]of longint;
35     l,r:longint;
36 
37 procedure work;
38 var
39     i:longint;
40 begin
41     l:=1;
42     r:=1;
43     q[1]:=1;
44     f[1]:=1;
45     while l<=r do
46       begin
47         i:=first[q[l]];
48         while i<>0 do
49           begin
50             f[last[i]]:=f[last[i]]+f[q[l]]/c[q[l]];
51             dis[last[i]]:=dis[last[i]]+dis[q[l]]/c[q[l]]+len[i]*f[q[l]]/c[q[l]];
52             dec(d[last[i]]);
53             if d[last[i]]=0 then
54             begin
55               inc(r);
56               q[r]:=last[i];
57             end;
58             i:=next[i];
59           end;
60         inc(l);
61       end;
62     writeln(dis[n]:0:2);
63 end;
64 
65 begin
66     init;
67     work;
68 end.
View Code
原文地址:https://www.cnblogs.com/Randolph87/p/3746355.html