标签:拓展 des log jks code style NPU out top
#include<iostream> #include<algorithm> #include<cstdio> #include<stack> using namespace std; const int maxn = 210; const int INF = 0x3f3f3f3f; int mp[maxn][maxn],vis[maxn],pre[maxn],dis[maxn],n,m,s,t; void dijkstra(int s){ for(int i = 0; i < n; i++){ dis[i] = mp[s][i]; vis[i] = 0; pre[i] = -1; } vis[s] = 1; dis[s] = 0; for(int i = 0; i < n; i++){ int minn = INF,u = 0; for(int j = 0; j < n; j++){ if(vis[j] == 0 && dis[j] < minn){ minn = dis[j]; u = j; } } vis[u] = 1; for(int j = 0; j < n; j++){ if(vis[j] == 0 && dis[u] + mp[u][j] < dis[j]){ dis[j] = dis[u] + mp[u][j]; pre[j] = u; } } } } int main(){ while(cin>>n>>m){ stack<int> St; for(int i = 0; i < n; i++){ for(int j = 0;j < n; j++){ mp[i][j] = INF; } } int u,v,w; for(int i = 0; i < m; i++){ cin>>u>>v>>w; if(w < mp[u][v]) //这个必须加上,这个无向图中两个点之间可能会有多条路,求最短的就行。还有,由于是无向图,所以mp[u][v] = mp[v][u] = w得都写上。 mp[u][v] = mp[v][u] = w; } cin>>s>>t; dijkstra(s); if(dis[t] == INF){ cout<<-1<<endl; } else{ cout<<dis[t]<<endl; } cout<<endl; } return 0; }
现在我特意进行拓展,打算使其能够输出最短路径,可以用stack。
C++代码:
#include<iostream> #include<algorithm> #include<cstdio> #include<stack> using namespace std; const int maxn = 210; const int INF = 0x3f3f3f3f; int mp[maxn][maxn],vis[maxn],pre[maxn],dis[maxn],n,m,s,t; void dijkstra(int s){ for(int i = 0; i < n; i++){ dis[i] = mp[s][i]; vis[i] = 0; pre[i] = -1; } vis[s] = 1; dis[s] = 0; for(int i = 0; i < n; i++){ int minn = INF,u = 0; for(int j = 0; j < n; j++){ if(vis[j] == 0 && dis[j] < minn){ minn = dis[j]; u = j; } } vis[u] = 1; for(int j = 0; j < n; j++){ if(vis[j] == 0 && dis[u] + mp[u][j] < dis[j]){ dis[j] = dis[u] + mp[u][j]; pre[j] = u; } } } } int main(){ while(cin>>n>>m){ stack<int> St; for(int i = 0; i < n; i++){ for(int j = 0;j < n; j++){ mp[i][j] = INF; } } int u,v,w; for(int i = 0; i < m; i++){ cin>>u>>v>>w; if(w < mp[u][v]) mp[u][v] = mp[v][u] = w; } cin>>s>>t; dijkstra(s); if(dis[t] == INF){ cout<<-1<<endl; } else{ cout<<dis[t]<<endl; printf("输出路径:\n"); int p = t; while(pre[p] != -1){ St.push(p); p = pre[p]; } St.push(p); cout<<s<<" "; while(!St.empty()){ int a = St.top(); cout<<a<<" "; St.pop(); } } cout<<endl; } return 0; }
参考链接:https://blog.csdn.net/renzijing/article/details/80572549
(Dijkstra 输出路径) HDU 1784 畅通工程续
标签:拓展 des log jks code style NPU out top
原文地址:https://www.cnblogs.com/Weixu-Liu/p/10896259.html