标签:图的遍历,数学期望
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
珍惜NOIP前最后的刷水机会2333
Code
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define dep(i,a,b) for(int i=a;i>=b;i--)
#define ll long long
#define mem(x,num) memset(x,num,sizeof x)
#ifdef WIN32
#define LL "%I64d"
#else
#define LL "%lld"
#endif
using namespace std;
inline ll read()
{
ll f=1,x=0;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
const int maxn=1e5+6;
int n,m,last[maxn],vis[maxn],r[maxn]={0};
struct edge{int to,next,w;}e[maxn<<1];
double f[maxn];
void dfs(int x)
{
if(!vis[x])vis[x]=1;
else return;
#define reg(x) for(int i=last[x];i;i=e[i].next)
#define v e[i].to
reg(x){
dfs(v);
f[x]+=e[i].w+f[v];
}
if(r[x])f[x]/=r[x];
}
int main()
{
n=read(),m=read();
rep(i,1,m){
int x=read(),y=read(),z=read();
e[i]=(edge){y,last[x],z};last[x]=i;
r[x]++;
}
dfs(1);
printf("%.2lf\n",f[1]);
return 0;
}