码迷,mamicode.com
首页 > 其他好文 > 详细

最短路 dijkstra()

时间:2020-02-01 20:57:40      阅读:50      评论:0      收藏:0      [点我收藏+]

标签:ace   jks   size   style   path   its   lse   return   c++   

  

 1 #include<bits/stdc++.h>
 2 #include<vector>
 3 #include<queue>
 4 using namespace std;
 5 
 6 const int inf = 0x3f3f3f3f;
 7 const int num = ???;
 8 struct edge{
 9     int from, to, w;
10     edge(int a, int b, int c){from=a; to=b; w=c;}
11 };
12 vector<edge>e[num];
13 struct node{
14     int id, n_dis;//id节点,n_dis节点到起点的距离
15     node(int b, int c){id=b; n_dis=c;}
16     bool operator <(const node &a)const
17     {    return n_dis > a.n_dis;}
18 };
19 int n, m, s;
20 int pre[num];
21 int dis[num];
22 bool done[num];
23 
24 void print_path(int s, int t){
25     if(s==t){printf("%d",s); return ;}
26     print_path(s, pre[t]);
27     printf("->%d",t);
28 }
29 
30 void dijkstra(){
31     //
32     s=  1;
33     for(int i=1; i<=n; ++i){
34         dis[i] = inf;
35         done[i] = false;
36     }
37     dis[s] = 0;
38     //
39     priority_queue<node>q;
40     q.push(node(s, dis[s]));
41     //
42     while(!q.empty()){
43         node u = q.top();
44         q.pop();
45         //
46         if(done[u.id])    continue;
47         //
48         done[u.id] = true;
49         for(int i=0; i<e[u.id].size(); ++i){
50             edge y = e[u.id][i];
51             //
52             if(done[y.to])    continue;
53             //
54             if(dis[y.to] > y.w + u.n_dis){
55                 dis[y.to] = y.w + u.n_dis;
56                 q.push(node(y.to, dis[y.to]));
57                 pre[y.to] = u.id;
58             }
59         }
60     }
61     //print_path(s,?);
62 }
63 
64 int main(){
65     while(~scanf("%d %d", &n, &m) && n && m){
66         //
67         for(int i=1; i<=n; ++i)        e[i].clear();
68         //
69         while(m--){
70             int a, b, c;
71             scanf("%d %d %d", &a, &b, &c);
72             e[a].push_back(edge(a, b, c));
73             e[b].push_back(edge(b, a, c));
74         }
75         //
76         dijkstra();
77     }
78     return 0;
79 }

 

最短路 dijkstra()

标签:ace   jks   size   style   path   its   lse   return   c++   

原文地址:https://www.cnblogs.com/0424lrn/p/12249807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!