路径长度
金牌导航 期望-1
题目大意
给出一个图,问你从1走到n的期望路径长度
输入样例
4 4
1 2 1
1 3 2
2 3 3
3 4 4
输出样例
7.00
数据范围
1⩽n⩽1051\leqslant n \leqslant 10^51⩽n⩽105
1⩽m⩽2×n1\leqslant m\leqslant 2\times n1⩽m⩽2×n
1⩽u,v⩽n1\leqslant u,v\leqslant n1⩽u,v⩽n
1⩽w⩽1091\leqslant w\leqslant 10^91⩽w⩽109
数据保证给出的图无重边和自环
解题思路
设f_x为经过x的期望次数
那么有
f1=1f_1=1f1=1
feto=fxdegxf_{eto}=\frac{f_x}{deg_x}feto=degxfx
然后用点的期望经过次数得出边的期望经过次数
然后乘上长度即可
代码
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long
#define N 100010
using namespace std;
int n, m, x, y, z, tot, head[N], indeg[N], outdeg[N];
double ans, f[N];
struct rec
{int l, to, next;
}a[2*N];
void add(int x, int y, int z)
{a[++tot].to = y;a[tot].next = head[x];a[tot].l = z;head[x] = tot;outdeg[x]++;indeg[y]++;
}
void solve()
{queue<int>d;d.push(1);f[1] = 1.0;while(!d.empty()){int h = d.front();d.pop();for (int i = head[h]; i; i = a[i].next){f[a[i].to] += f[h] / outdeg[h];//期望经过次数indeg[a[i].to]--;ans += f[h] /outdeg[h] * a[i].l;//计算贡献if (!indeg[a[i].to]) d.push(a[i].to);}}return;
}
int main()
{scanf("%d%d", &n, &m);for (int i = 1; i <= m; ++i){scanf("%d%d%d", &x, &y, &z);add(x, y, z);}solve();printf("%.2lf", ans);return 0;
}