Advertisement
tepyotin2

Shortest Route I

May 25th, 2025
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6.  
  7. struct Edge{
  8.     int to;
  9.     ll weight;
  10. };
  11.  
  12. struct Node{
  13.     int node;
  14.     ll weight;
  15.     bool operator>(const Node &a) const{
  16.         return weight>a.weight;
  17.     }
  18. };
  19.  
  20. ll INF = LLONG_MAX;
  21. int n, m;
  22. vector<vector<Edge>> con;
  23. priority_queue<Node, vector<Node>, greater<Node>> pq;
  24.  
  25. int main(){
  26.     //freopen("shortestroute.in", "r", stdin);
  27.    
  28.     cin >> n >> m;
  29.     con.resize(n+1);
  30.     vector<long long> dist(n+1, INF);
  31.     for(int i=0; i<m; i++){
  32.         int a, b, c;
  33.         cin >> a >> b >> c;
  34.         con[a].push_back({b, c});
  35.         //con[b].push_back({a, c});
  36.     }
  37.     pq.push({1, 0});
  38.     dist[1] = 0;
  39.     while(!pq.empty()){
  40.         Node cur = pq.top();
  41.         pq.pop();
  42.         int weight = cur.weight;
  43.         int node = cur.node;
  44.         if(weight>dist[node]) continue;
  45.         for(Edge e: con[node]){
  46.             if(dist[e.to]>dist[node]+e.weight){
  47.                 //cout << "HI" << '\n';
  48.                 dist[e.to] = dist[node]+e.weight;
  49.                 //cout << dist[e.to] << '\n';
  50.                 pq.push({e.to, dist[e.to]});
  51.             }
  52.         }
  53.     }
  54.     string s = "";
  55.     for(int i=1; i<=n; i++){
  56.         cout << s << dist[i];
  57.         s = " ";
  58.     }
  59.     cout << '\n';
  60.    
  61.     return 0;
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement