很显然这个题目考期望(废话
期望的题目基本都是 d p dp dp 题
设 f [ x ] f[x] f[x] 表示到达节点 x x x 走到终点的路径的期望长度
若从 x x x 出发的路径有 k k k 条,分别去 y 1 , y 2 , . . . y k y_1,y_2,...y_k y1,y2,...yk,长度分别为 z 1 , z 2 , . . . z k z_1,z_2,...z_k z1,z2,...zk,通过期望的线性性我们可以列出 d p dp dp 转移方程
f [ x ] = 1 k ∑ i = 1 k ( f [ y i ] + z i ) f[x]=\frac{1}{k}\sum\limits_{i=1}^k(f[y_i]+z_i) f[x]=k1i=1∑k(f[yi]+zi)
初始显然 f [ n ] = 0 f[n]=0 f[n]=0,答案就是 f [ 1 ] f[1] f[1]
我们在反图上跑拓扑排序即可完成此题
时间复杂度 O ( n + m ) O(n+m) O(n+m)
#include <map>
#include <set>
#include <ctime>
#include <queue>
#include <stack>
#include <cmath>
#include <vector>
#include <bitset>
#include <cstdio>
#include <cctype>
#include <string>
#include <numeric>
#include <cstring>
#include <cassert>
#include <climits>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <functional>
using namespace std ;
#define rep(i, a, b) for (int i = (a); i <= (b); i++)
#define per(i, a, b) for (int i = (a); i >= (b); i--)
#define loop(s, v, it) for (s::iterator it = v.begin(); it != v.end(); it++)
#define cont(i, x) for (int i = head[x]; i; i = e[i].nxt)
#define clr(a) memset(a, 0, sizeof(a))
#define ass(a, sum) memset(a, sum, sizeof(a))
#define lowbit(x) (x & -x)
#define all(x) x.begin(), x.end()
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define iv inline void
#define enter cout << endl
#define siz(x) ((int)x.size())
#define file(s) freopen(s".in", "r", stdin), freopen(s."out", "w", stdout)
typedef long long ll ;
typedef unsigned long long ull ;
typedef pair <int, int> pii ;
typedef vector <int> vi ;
typedef vector <pii> vii ;
typedef queue <int> qi ;
typedef set <int> si ;
typedef map <int, int> mii ;
typedef map <string, int> msi ;
const int N = 100010 ;
const int INF = 0x3f3f3f3f ;
const int iinf = 1 << 30 ;
const ll linf = 2e18 ;
const int MOD = 1000000007 ;
const double eps = 1e-7 ;
void print(int x) { cout << x << endl ; exit(0) ; }
void PRINT(string x) { cout << x << endl ; exit(0) ; }
void douout(double x){ printf("%lf\n", x + 0.0000000001) ; }
double dis[N] ;
int head[N], deg[N], in[N] ;
int n, m, top = 1 ;
qi q ;
struct Edge {
int to, nxt, w ;
} e[N << 1] ;
void add(int a, int b, int w) {
e[++top] = (Edge) {b, head[a], w} ;
head[a] = top ;
}
signed main(){
scanf("%d%d", &n, &m) ;
rep(i, 1, m) {
int x, y, z ; scanf("%d%d%d", &x, &y, &z) ;
add(y, x, z) ;
in[x]++ ; deg[x]++ ;
}
q.push(n) ;
while (!q.empty()) {
int now = q.front() ; q.pop() ;
cont(i, now) {
int y = e[i].to ;
dis[y] += (dis[now] + e[i].w) / deg[y] ;
in[y]-- ;
if (!in[y]) q.push(y) ;
}
}
printf("%.2lf\n", dis[1]) ;
return 0 ;
}
/*
写代码时请注意:
1.ll?数组大小,边界?数据范围?
2.精度?
3.特判?
4.至少做一些
思考提醒:
1.最大值最小->二分?
2.可以贪心么?不行dp可以么
3.可以优化么
4.维护区间用什么数据结构?
5.统计方案是用dp?模了么?
6.逆向思维?
*/