Advertisement
Josif_tepe

Untitled

Dec 8th, 2024
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <unordered_map>
  5. #include <queue>
  6. using namespace std;
  7. const int maxn = 1e5 + 10;
  8. int n;
  9. vector<pair<int, int>> graph[maxn];
  10. struct node {
  11.     int idx, cost;
  12.     node () {}
  13.     node(int _idx, int _cost) {
  14.         idx = _idx;
  15.         cost = _cost;
  16.     }
  17.    
  18.     bool operator < (const node & tmp) const {
  19.         return cost > tmp.cost;
  20.     }
  21.    
  22. };
  23.  
  24. void dijkstra(int S) {
  25.     vector<bool> visited(n, false);
  26.     vector<int> dist(n, 2e9);
  27.    
  28.     dist[S] = 0;
  29.     priority_queue<node> pq;
  30.     pq.push(node(S, 0));
  31.    
  32.     while(!pq.empty()) {
  33.         node c = pq.top();
  34.         pq.pop();
  35.        
  36.         if(visited[c.idx]) continue;
  37.         visited[c.idx] = true;
  38.        
  39.         for(int i = 0; i < (int) graph[c.idx].size(); i++) {
  40.             int neighbour = graph[c.idx][i].first;
  41.             int weight = graph[c.idx][i].second;
  42.            
  43.             if(!visited[neighbour] and c.cost + weight < dist[neighbour]) {
  44.                 dist[neighbour] = c.cost + weight;
  45.                 pq.push(node(neighbour, c.cost + weight));
  46.             }
  47.         }
  48.     }
  49.     for(int i = 0; i < n; i++) {
  50.         cout << i << ": " << dist[i] << endl;
  51.     }
  52.    
  53. }
  54. int main()
  55. {
  56.     int  m;
  57.     cin >> n >> m;
  58.    
  59.     for(int i = 0; i < m; i++) {
  60.         int a, b, c;
  61.         cin >> a >> b >> c;
  62.         graph[a].push_back(make_pair(b, c));
  63.         graph[b].push_back(make_pair(a, c));
  64.     }
  65.     dijkstra(0);
  66.    
  67.  
  68.     return 0;
  69.  
  70. }
  71.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement