單源最短路徑—Dijkstra 演算法–路徑還原

來源:互聯網
上載者:User
#include <iostream>#include <algorithm>#include <cstring>#include <vector>#include <fstream>using namespace std;const int maxn=100;const int INF=999999;int pre[maxn];bool visited[maxn];int d[maxn],cost[maxn][maxn],n,m; //n vertexs,1,2,...n. m edges.void dijkstra(int s){memset(pre,-1,sizeof(pre));fill(d+1,d+1+n,INF);memset(visited,0,sizeof(visited));d[s]=0;while(1){int index=-1;for(int u=1;u<=n;u++){if(!visited[u] && (index==-1|| d[u]<d[index]))index=u;}if(index==-1)break;visited[index]=1;for(int u=1;u<=n;u++){if( d[u]>d[index]+cost[index][u]){d[u]=d[index]+cost[index][u];pre[u]=index;}}}}vector<int> get_path(int t){vector<int> path;path.clear();for(;t!=-1;t=pre[t]){path.push_back(t);}reverse(path.begin(),path.end());return path;} int main(){ifstream fin;fin.open("input.txt");cout<<fin.is_open()<<endl;while(fin>>n>>m){for(int i=1;i<=n;i++)       //這裡一定要進行預先處理 for(int j=1;j<=n;j++){if(i==j)cost[i][j]=0;else cost[i][j]=INF;}for(int i=1;i<=m;i++){int u,v,c;fin>>u>>v>>c;cost[u][v]=c; //DAG}int s,t;fin>>s>>t;dijkstra(s);cout<<"the shortest path from "<<s<<" to "<<t<<" is: "<<d[t]<<endl;cout<<"the path is :"<<endl;vector<int> path=get_path(t); //得到最短路徑 for(int i=0;i!=path.size();i++)cout<<path[i]<<" ";cout<<endl;}}

給出一組測試:

5
7
1 2 10
1 4 30
1 5 100
2 3 50
3 5 10
4 3 20
4 5 60

1 5

輸出結果:

1

the shortest path from 1 to 5 is :60

the path is :

1 4 3 5

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.