需要使用记忆话,一个点的期望只去计算一次。
#include <stdio.h> #include <cstring> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <iostream> #include <map> #define go(i, l, r) for(int i = (l), i##end = (int)(r); i <= i##end; ++i) #define god(i, r, l) for(int i = (r), i##end = (int)(l); i >= i##end; --i) #define ios ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0) #define debug_in freopen("in.txt","r",stdin) #define debug_out freopen("out.txt","w",stdout); #define pb push_back #define all(x) x.begin(),x.end() #define fs first #define sc second using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<ll,ll> pii; const ll maxn = 1e5+10; const ll maxM = 1e6+10; const ll inf_int = 1e8; const ll inf_ll = 1e17; template<class T>void read(T &x){ T s=0,w=1; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();} while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar(); x = s*w; } template<class H, class... T> void read(H& h, T&... t) { read(h); read(t...); } void pt(){ cout<<'\n';} template<class H, class ... T> void pt(H h,T... t){ cout<<" "<<h; pt(t...);} //-------------------------------------------- int N,M; int h[maxn],w[maxn*2],e[maxn*2],ne[maxn*2],idx = 1; int sz[maxn]; double rec[maxn]; void add(int a,int b,int c){ e[++idx] = b; w[idx] = c; ne[idx] = h[a]; h[a] = idx; } double E[maxn]; void dfs(int u){ if(rec[u]>=0) return ;//记录一下,算过的期望就不要再算,不然算重,多加了。 for(int i = h[u];i;i = ne[i]){ int v = e[i]; dfs(v); E[u] += 1.0 * (E[v] + w[i])/(double)sz[u]; } rec[u] = E[u]; } int main() { // debug_in; // debug_out; read(N,M); for(int i = 1;i<=M;i++){ int x,y,z;read(x,y,z); add(x,y,z); sz[x]++; } memset(rec,-1,sizeof rec); dfs(1); printf("%.2f\n",E[1]); return 0; }