【BZOJ3036】绿豆蛙的归宿 概率与期望

最水的概率期望,推荐算法合集之《浅析竞赛中一类数学期望问题的解决方法》

 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 #define N 100010
 5 #define M 200020
 6 struct E
 7 {
 8     int next,to,v;
 9 }e[M];
10 double f[N];
11 int head[N],vis[N],oute[N];
12 int n,m,cnt;
13 inline int read()
14 {
15     int ans=0,f=1;
16     char c;
17     while (!isdigit(c=getchar())) {if (c=='-') f=-1;}
18     ans=c-'0';
19     while (isdigit(c=getchar())) ans=ans*10+c-'0';
20     return ans*f;
21 }
22 inline void insert(int x,int y,int w)
23 {cnt++; e[cnt].next=head[x]; head[x]=cnt; e[cnt].to=y; e[cnt].v=w;}
24 void dfs(int x)
25 {
26     if (!vis[x]) vis[x]=1;
27     else return;
28     for (int i=head[x];i;i=e[i].next)
29     {
30         dfs(e[i].to);
31         f[x]+=e[i].v+f[e[i].to];
32     }
33     if (oute[x]) f[x]/=oute[x];
34 }
35 int main()
36 {
37     n=read(); m=read();
38     for (int i=1;i<=m;i++)
39     {
40         int x,y,w;
41         x=read(); y=read(); w=read();
42     //    printf("%d %d %d ",x,y,w); 
43         insert(x,y,w);
44         oute[x]++;
45     }
46     dfs(1);
47     printf("%.2lf
",f[1]);
48     return 0;
49 }
View Code

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

Source

—Anime Otaku Save The World.
原文地址:https://www.cnblogs.com/DMoon/p/5349947.html