Acwing 217. 绿豆蛙的归宿
生活随笔
收集整理的這篇文章主要介紹了
Acwing 217. 绿豆蛙的归宿
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Acwing 217. 綠豆蛙的歸宿
題意:
給出一個有向無環的連通圖,起點為 1,終點為 N,每條邊都有一個長度。
數據保證從起點出發能夠到達圖中所有的點,圖中所有的點也都能夠到達終點。
綠豆蛙從起點出發,走向終點。
到達每一個頂點時,如果有 K 條離開該點的道路,綠豆蛙可以選擇任意一條道路離開該點,并且走向每條路的概率為 1/K。
現在綠豆蛙想知道,從起點走到終點所經過的路徑總長度的期望是多少?
題解:
這個文章講的不錯
設dp[x]表示狀態為x到終點n的期望路徑總長,顯然dp[n] = 0,所以要從dp[n]倒著推dp[1]
我們設一條有向邊,x->y,那么就有:
dp[x] = P * ∑dp[y] + w[x->y]
P = (1/degree(x)),degree(x)為x的出度,有多少出度說明有多少種選擇,概率就是倒數
w表示轉移對答案的貢獻
dp可以通過記憶化搜索求,也就通過拓撲排序求
代碼:
記憶化搜索
#include<bits/stdc++.h> #define debug(a,b) printf("%s = %d\n",a,b); typedef long long ll; using namespace std;inline int read(){int 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();//s=(s<<3)+(s<<1)+(ch^48);return s*w; } const int maxn=3e5+9; vector<pair<int,int> >vec[maxn]; double dp[maxn]; int n,m; double dfs(int u){if(u==n)return 0;if(dp[u])return dp[u];for(int i=0;i<vec[u].size();i++){int v=vec[u][i].first;int w=vec[u][i].second;dp[u]+=dfs(v)+w;}dp[u]=dp[u]/int(vec[u].size());return dp[u]; } int main() {cin>>n>>m;for(int i=1;i<=m;i++){int u,v,w;cin>>u>>v>>w;vec[u].push_back({v,w});}printf("%.2f",dfs(1)); }拓撲排序
時間復雜度O(n+m)
#include<iostream> #include<cstdio> #include<cmath> #include<algorithm> #include<queue> #include<cstring> using namespace std; typedef long long ll; const int inf=1e9+7; inline int read()//讀優 {int p=0,f=1;char c=getchar();while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}while(c>='0'&&c<='9'){p=p*10+c-'0';c=getchar();}return f*p;} const int maxn=100003; const int maxm=200003; struct Edge {int from,to,w; }p[maxm]; int n,m,cnt,head[maxm],in[maxn],dg[maxn]; double f[maxn];//f[x]表示x點到終點n的期望路徑總長 inline void add_edge(int x,int y,int W)//加邊 {cnt++;p[cnt].from=head[x];head[x]=cnt;p[cnt].to=y;p[cnt].w=W; } inline void toposort()//拓撲排序 {queue <int> q;q.push(n);while(!q.empty()){int x=q.front();q.pop();for(int i=head[x];i;i=p[i].from){int y=p[i].to;f[y]+=(f[x]+p[i].w)/dg[y];//dp轉移 if(!(--in[y]))q.push(y);}} } int main() {n=read(),m=read();for(int i=1;i<=m;i++){int x=read(),y=read(),w=read();add_edge(y,x,w);//反向建圖 in[x]++,dg[x]++;}toposort();printf("%.2lf\n",f[1]);return 0; }總結
以上是生活随笔為你收集整理的Acwing 217. 绿豆蛙的归宿的全部內容,希望文章能夠幫你解決所遇到的問題。