willy108

Pay Attention in Class

Jul 25th, 2024
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4.  
  5. using namespace std;
  6. using ll = long long;
  7.  
  8. int main() {
  9. int n, m; cin >> n >> m;
  10.  
  11. vector<vector<pair<ll, int>>> adj(n);
  12. for (int i = 0; i < m; i++) {
  13. int u, v; ll w; cin >> u >> v >> w; u--; v--;
  14.  
  15. adj[u].push_back({ v, w });
  16. }
  17.  
  18. vector<ll> dists(n, LLONG_MAX); // final answer
  19.  
  20. vector<bool> visited(n); // (because we're keeping dups in pq)
  21.  
  22. using T = pair<ll, int>;
  23. priority_queue<T, vector<T>, greater<T>> pq;
  24. pq.push({ 0, 0 });
  25.  
  26. while (!pq.empty()) {
  27. auto nxt = pq.top();
  28. ll dist = nxt.first; int node = nxt.second;
  29. //cout << "Processing: {" << node << ", " << dist << "}\n";
  30. pq.pop();
  31.  
  32. if (visited[node]) continue;
  33. dists[node] = dist; // if we're visiting this for the first time, we're certain that this is the shortest dist
  34. visited[node] = true;
  35.  
  36. for (auto neighbor : adj[node]) { // neighbor = {Adjacent node, Distance to that node}
  37. pq.push({ dist + neighbor.second, neighbor.first });
  38. }
  39. }
  40.  
  41. for (int i = 0; i < n; i++) if (dists[i] == LLONG_MAX) dists[i] = -1;
  42.  
  43. for (int i = 0; i < n-1; i++) cout << dists[i] << " ";
  44. cout << dists[n - 1] << endl;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment