聖誕島的旅行Problem

來源:互聯網
上載者:User

聖誕島的旅行Problem
Angel最近無聊,去了聖誕島(CX *^_^*),他喜歡無目的的亂逛,當然,他不會輕易地回頭。Angel想去廣場,那麼,他什麼時候才能到呢?你已經得到了CX的地圖,地圖上有N(N <= 100)個交叉路口,交叉路口之間有馬路相串連(不超過1000條馬路)。因為CX的人遵循奇怪的規則,道路都是單向的,不同的道路之間有一定的距離,我們假設Angel所在的地點為點1,廣場所在點為N。假設Angel走一單位距離需要一單位時間。問Angel最早和最遲什麼時候到達廣場?

Input
本題有多組資料,第一行N, M,M是邊的數量以後M行,每行3個整數X, Y, Weight,代表一條從X城市到Y城市,長度為Wweight的邊。

Output
每組資料,第一行是最少時間,第二行是最遲時間,要是可憐的Angel可能永遠到不了廣場,輸出一行Never。

Sample Input
5 5
1 2 1
1 4 10
2 3 1
3 4 1
4 5 1

Sample Output
4
11

 

思路:使用遞迴函式:從起點開始,遍曆列表,找到以該點為起點的路徑,並確定下個起點中是否有目標點,同時計算路徑長度,再以下個起點為目標地址,以此迴圈下次,遍曆所有可能的路徑。

#include<iostream></p><p>using namespace std;</p><p>class Path<br />{<br />private:<br />int X,Y,Weight;</p><p>public:<br />void Input()<br />{<br />cin>>X;<br />cin>>Y;<br />cin>>Weight;<br />}</p><p>int GetX() const {return X;}<br />int GetY() const {return Y;}<br />int GetWeight() const {return Weight;}<br />};</p><p>void Travel(Path* p,int state,int end,int M,int &sum,int& shortest,int& longest,int& path)<br />{<br />//Path* p1=p;<br />for(int i=0;i<M;i++)<br />{</p><p>if(state==(p+i)->GetX())<br />{<br />sum+=(p+i)->GetWeight();<br />//cout<<(p+i)->GetX()<<" "<<(p+i)->GetY()<<" "<<(p+i)->GetWeight()<<" "<<sum<<endl;<br />if(end==(p+i)->GetY())<br />{<br />path++;<br />if(sum<shortest)<br />shortest=sum;<br />if(sum>longest)<br />longest=sum;<br />//cout<<shortest<<endl;<br />//cout<<longest<<endl;<br />}<br />else<br />{<br />Travel(p,(p+i)->GetY(),end,M,sum,shortest,longest,path);<br />sum-=(p+i)->GetWeight();<br />}</p><p>}</p><p>}<br />}</p><p>int main()<br />{<br />int start,end,path,M;<br />start=1;//預設起點為1<br />path=0;</p><p>cin>>end;<br />cin>>M;</p><p>Path* p=new Path[M];</p><p>for(int i=0;i<M;i++)<br />p[i].Input();</p><p>int shortest,longest,sum;<br />longest=0;<br />shortest=0;<br />sum=0;</p><p>for(i=0;i<M;i++)<br />shortest+=p[i].GetWeight();</p><p>Travel(p,1,end,M,sum,shortest,longest,path);</p><p>if(path==0)<br />cout<<"Never"<<endl;<br />else<br />{<br />cout<<shortest<<endl;<br />cout<<longest<<endl;<br />}</p><p>delete[] p;<br />return 0;<br />}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.