Josif_tepe

Untitled

Aug 19th, 2025
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.70 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <functional>
  5. using namespace std;
  6. const int maxn = 1e5 + 5;
  7. const int INF = 2e9;
  8. int n, m;
  9. vector<pair<int, int>> graph[maxn];
  10.  
  11. void dijkstra(int start_node, int end_node) {
  12.     vector<bool> visited(n, false);
  13.     vector<int> shortest_distance(n, INF);
  14.    
  15.     shortest_distance[start_node] = 0;
  16.     priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
  17.    
  18.     pq.push({start_node ,0});
  19.    
  20.     while(!pq.empty()) {
  21.         pair<int, int> p = pq.top();
  22.         pq.pop();
  23.         int current_node = p.first;
  24.         int current_node_path = p.second;
  25.        
  26.         if(visited[current_node]) {
  27.             continue;
  28.         }
  29.        
  30.         if(current_node == end_node) {
  31.             cout << current_node_path << endl;
  32.             return;
  33.         }
  34.         visited[current_node] = true;
  35.        
  36.         for(pair<int, int> neighbour : graph[current_node]) {
  37.             int neighbour_node = neighbour.first;
  38.             int neighbour_weight = neighbour.second;
  39.            
  40.             if(!visited[neighbour_node] and current_node_path + neighbour_weight < shortest_distance[neighbour_node]) {
  41.                 pq.push({neighbour_node, current_node_path + neighbour_weight});
  42.                 shortest_distance[neighbour_node] = current_node_path + neighbour_weight;
  43.             }
  44.         }
  45.        
  46.        
  47.     }
  48.    
  49. }
  50. int main() {
  51.     cin >> n >> m;
  52.    
  53.     for(int i = 0; i < m; i++) {
  54.         int a, b, c;
  55.         cin >> a >> b >> c;
  56.        
  57.         graph[a].push_back({b, c});
  58.         graph[b].push_back({a, c});
  59.     }
  60.    
  61.     dijkstra(0, 4);
  62.    
  63.     return 0;
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment