Advertisement
Josif_tepe

Untitled

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