数据加强版的最短路
洛谷链接:https://www.luogu.org/problem/P4779
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <vector> 5 #include <queue> 6 using namespace std; 7 typedef pair<int, int> PII; 8 const int N = 1e5 + 10; 9 const int INF = 2147483647; 10 11 int n, m, s; 12 int dist[N]; 13 vector<PII> g[N]; 14 int vis[N]; 15 16 void dijkstra() 17 { 18 memset(vis, 0, sizeof(vis)); 19 for(int i = 1; i <= n; i++) dist[i] = INF; 20 dist[s] = 0; 21 //优先队列 22 priority_queue<PII> q; 23 q.push({0, s}); 24 while(!q.empty()) 25 { 26 int node = q.top().second; q.pop(); 27 if(vis[node] == 1) continue; 28 vis[node] = 1; 29 for(int i = 0; i < g[node].size(); i++) 30 { 31 int tmpNode = g[node][i].second; 32 if(dist[tmpNode] > dist[node] + g[node][i].first) 33 { 34 dist[tmpNode] = dist[node] + g[node][i].first; 35 //注意,这里是把距离的负数压入队列,因为是大根堆,这样最短距离就在队首了 36 q.push({-dist[tmpNode], tmpNode}); 37 } 38 } 39 } 40 } 41 42 int main() 43 { 44 cin >> n >> m >> s; 45 for(int i = 1; i <= m; i++) 46 { 47 int u, v, d; 48 scanf("%d %d %d", &u, &v, &d); 49 g[u].push_back({d, v}); 50 } 51 dijkstra(); 52 for(int i = 1; i <= n; i++) 53 i==1?cout<<dist[i]:cout<<" "<<dist[i]; 54 return 0; 55 }