Dijkstra模板

 1 //
 2 //  dijkstra模板.cpp
 3 //  algorithm
 4 //
 5 //  Created by david.xu on 2018/8/6.
 6 //  Copyright © 2018年 Amorphophallus-Konjac. All rights reserved.
 7 //
 8 
 9 #include <stdio.h>
10 #include <cstdlib>
11 #include <cstring>
12 #include <cmath>
13 #include <iostream>
14 #include <algorithm>
15 #include <queue>
16 #include <vector>
17 #define maxn 100010
18 #define pa pair<int,int>
19 
20 using namespace std;
21 
22 int n,m,s,dis[maxn];
23 bool vis[maxn];
24 
25 priority_queue<pa,vector<pa>,greater<pa> > q;
26 
27 struct edge{
28     int val,to;
29 };
30 vector<edge> e[maxn];
31 
32 void dijkstra()
33 {
34     for(int i=1;i<=n;i++)
35         dis[i]=1000000001;
36     dis[s]=0;
37     q.push(make_pair(0, s));
38     while(!q.empty())
39     {
40         int x=q.top().second;
41         q.pop();
42         if(vis[x])
43             continue;
44         vis[x]=1;
45         for(int i=0;i<e[x].size();i++)
46         {
47             int y=e[x][i].to;
48             if(dis[x]+e[x][i].val<dis[y])
49             {
50                 dis[y]=dis[x]+e[x][i].val;
51                 q.push(make_pair(dis[y], y));
52             }
53         }
54     }
55 }
56 
57 int main()
58 {
59     scanf("%d%d%d",&n,&m,&s);
60     for(int i=1;i<=m;i++)
61     {
62         int x,y,z;
63         scanf("%d%d%d",&x,&y,&z);
64         edge tmp;
65         tmp.to=y;
66         tmp.val=z;
67         e[x].push_back(tmp);
68     }
69     dijkstra();
70     for(int i=1;i<=n;i++)
71         printf("%d ",dis[i]);
72     return 0;
73 }
原文地址:https://www.cnblogs.com/Amorphophallus-Konjac-blog/p/11233807.html