31.绿豆蛙的归宿(拓扑排序)
?時(shí)間限制: 1 s
?空間限制: 64000 KB
?題目等級 : 黃金 Gold
題解
題目描述?Description
隨著新版百度空間的上線,Blog寵物綠豆蛙完成了它的使命,去尋找它新的歸宿。
給出一個(gè)有向無環(huán)圖,起點(diǎn)為1終點(diǎn)為N,每條邊都有一個(gè)長度,并且從起點(diǎn)出發(fā)能夠到達(dá)所有的點(diǎn),所有的點(diǎn)也都能夠到達(dá)終點(diǎn)。綠豆蛙從起點(diǎn)出發(fā),走向終點(diǎn)。
到達(dá)每一個(gè)頂點(diǎn)時(shí),如果有K條離開該點(diǎn)的道路,綠豆蛙可以選擇任意一條道路離開該點(diǎn),并且走向每條路的概率為?1/K?。
現(xiàn)在綠豆蛙想知道,從起點(diǎn)走到終點(diǎn)的所經(jīng)過的路徑總長度期望是多少?
輸入描述?Input Description
第一行:?兩個(gè)整數(shù)?N?M,代表圖中有N個(gè)點(diǎn)、M條邊
第二行到第?1+M?行:?每行3個(gè)整數(shù)?a?b?c,代表從a到b有一條長度為c的有向邊
輸出描述?Output Description
從起點(diǎn)到終點(diǎn)路徑總長度的期望值,四舍五入保留兩位小數(shù)。
樣例輸入?Sample Input
4 4
1 2 1
1 3 2
2 3 3
3 4 4
樣例輸出?Sample Output
7.00
數(shù)據(jù)范圍及提示?Data Size & Hint
對于20%的數(shù)據(jù)???N<=100
對于40%的數(shù)據(jù)???N<=1000
對于60%的數(shù)據(jù)???N<=10000
對于100%的數(shù)據(jù)??N<=100000,M<=2*N
代碼:
(當(dāng)輸入數(shù)據(jù)數(shù)量接近邊界最大值時(shí),會(huì)超時(shí),要開很大的數(shù)組時(shí),最好用動(dòng)態(tài)數(shù)組解決,節(jié)省時(shí)間)
#include
using namespace std;
#include
#include
#define maxn 100001
int rudu[maxn],chudu[maxn],ans[maxn],a,b,c;
struct Edge{
?????? int u,v,w,next;
};
Edge edge[2*maxn];
int head[maxn]={0},n,m;
double sumhope=0,rate[maxn];
void input();
void topsort();
int main()
{
?????? input();
?????? topsort();
?????? printf("%.2lf",sumhope);
?????? return 0;
}
void topsort()
{
?????? int tot=0;
?????? int t;
?????? t=0;
?????? for(int i=1;i<=n;++i)
??? if(!rudu[i])
?? ? {
?? ???????? t++;
????????????? tot++;
????????????? rudu[i]=99999;
????????????? rate[i]=1;
????????????? ans[t]=i;
?????? ?? }
?????? while(tot
?????? {
????????????? for(int i=1;i<=t;++i)
????????????? ? for(int j=head[ans[i]];j!=0;j=edge[j].next)
????????????? ? {
????????????? ? ??? rudu[edge[j].v]--;
????????????? ? ??? rate[edge[j].v]+=rate[ans[i]]/chudu[ans[i]];
????????????? ? ??? sumhope+=(rate[ans[i]]/chudu[ans[i]])*edge[j].w;
????????????? ? }
????????????? t=0;
????????????? for(int i=1;i<=n;++i)
???????????????????? if(!rudu[i])
?????? ????????????? {
??????????????????????????? rudu[i]=99999;
??????????????????????????? t++;
??????????????????????????? tot++;
??????????????????????????? ans[t]=i;
???????????????????? }
?????????????
??????
?????? }
}
void input()
{
?????? scanf("%d%d",&n,&m);
?????? for(int i=1;i<=m;++i)
?????? {
????????????? scanf("%d%d%d",&a,&b,&c);
????????????? edge[i].u=a;
????????????? edge[i].v=b;
????????????? edge[i].w=c;
????????????? rudu[b]++;
????????????? chudu[a]++;
????????????? edge[i].next=head[a];
????????????? head[a]=i;
?????? }
}
轉(zhuǎn)載于:https://www.cnblogs.com/csgc0131123/p/5290473.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的31.绿豆蛙的归宿(拓扑排序)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MapReduce自定义二次排序流程
- 下一篇: 生成 PDF 全攻略【1】初体验