1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn = 10005; 4 struct edge { 5 int v, w; 6 }; 7 vector<edge> maps[maxn]; 8 int dis[maxn]; 9 bool vis[maxn]; 10 int n, m, s; 11 void add(int u, int v, int w) { 12 maps[u].push_back(edge{v,w}); 13 } 14 void spfa(int s) { 15 for (int i = 1; i <= n; i++) { 16 dis[i] = 2147483647; 17 vis[i] = false; 18 } 19 queue<int> que; 20 que.push(s), dis[s] = 0, vis[s] = true; 21 while(!que.empty()) { 22 int u = que.front(); 23 que.pop(); 24 vis[u] = false; 25 for(int i = 0; i < maps[u].size(); i++) { 26 int v = maps[u][i].v; 27 int w = maps[u][i].w; 28 if(dis[v] > dis[u]+w) { 29 dis[v] = dis[u] + w; 30 if(vis[v] == false) { 31 que.push(v); 32 vis[v] = true; 33 } 34 } 35 } 36 } 37 } 38 int main() { 39 scanf("%d%d%d",&n,&m,&s); 40 for(int i = 1; i <= m; i++) { 41 int u, v, w; scanf("%d%d%d",&u,&v,&w); 42 add(u,v,w); 43 } 44 spfa(s); 45 printf("%d",dis[1]); 46 for (int i = 2; i <= n; i++) 47 printf(" %d",dis[i]); 48 printf("\n"); 49 return 0; 50 }
spfa
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 const int maxn = 10005, 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 }
dijkstra
原文地址:https://www.cnblogs.com/wstong/p/11745272.html
时间: 2024-10-09 08:23:43