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

P4779 【模板】单源最短路径(标准版)

时间:2019-10-26 20:49:54      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:turn   color   set   empty   space   单源最短路径   def   max   eof   

P4779 【模板】单源最短路径(标准版)

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 const int maxn = 1e5+5, inf = 0x3f3f3f3f;
 5 struct Edge {
 6     int from, to, dist;
 7 };
 8 struct HeapNode {
 9     int d, u;
10     bool operator < (const HeapNode& rhs) const {
11         return d > rhs.d;
12     }
13 };
14 struct Dijkstra {
15     int n, m;
16     vector<Edge> edges;
17     vector<int> G[maxn];
18     bool done[maxn];
19     int d[maxn];
20     int p[maxn];
21 
22     void init(int n) {
23         this->n = n;
24         for (int i = 1; i <= n; i++) G[i].clear();
25         edges.clear();
26     }
27 
28     void AddEdge(int from, int to, int dist) {
29         edges.push_back((Edge){from, to, dist});
30         m = edges.size();
31         G[from].push_back(m-1);
32     }
33     void dijkstra(int s) {
34         priority_queue<HeapNode> Q;
35         for (int i = 1; i <= n; i++) d[i] = inf;
36         d[s] = 0;
37         memset(done, 0, sizeof(done));
38         Q.push((HeapNode){0, s});
39         while (!Q.empty()) {
40             HeapNode x = Q.top(); Q.pop();
41             int u = x.u;
42             if (done[u]) continue;
43             done[u] = true;
44             for (int i = 0; i < G[u].size(); i++) {
45                 Edge & e = edges[G[u][i]];
46                 if (d[e.to] > d[u] + e.dist) {
47                     d[e.to] = d[u] + e.dist;
48                     p[e.to] = G[u][i];
49                     Q.push((HeapNode){d[e.to], e.to});
50                 }
51             }
52         }
53     }
54 };
55 int main() {
56     int n, m, s; scanf("%d%d%d",&n,&m,&s);
57     Dijkstra dij;
58     dij.init(n);
59     for (int i = 1; i <= m; i++) {
60         int u, v, w; scanf("%d%d%d",&u,&v,&w);
61         dij.AddEdge(u,v,w);
62     }
63     dij.dijkstra(s);
64     printf("%d",dij.d[1]==inf ? 2147483647 : dij.d[1]);
65     for (int i = 2; i <= n; i++)
66         printf(" %d",dij.d[i]==inf ? 2147483647 : dij.d[i]);
67     printf("\n");
68     return 0;
69 }

 

P4779 【模板】单源最短路径(标准版)

标签:turn   color   set   empty   space   单源最短路径   def   max   eof   

原文地址:https://www.cnblogs.com/wstong/p/11745302.html

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