Josif_tepe

Untitled

Sep 10th, 2025
214
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 <queue>
  4. using namespace std;
  5. const int maxn = 1e5 + 10;
  6. const int INF = 2e9;
  7. vector<pair<int, int>> graph[maxn];
  8.  
  9.  
  10. int main() {
  11.     ios_base::sync_with_stdio(false);
  12.     int n, m;
  13.     cin >> n >> m;
  14.    
  15.     for(int i = 0; i < m; i++) {
  16.         int a, b, c;
  17.         cin >> a >> b >> c;
  18.        
  19.         graph[a].push_back({b, c});
  20.         graph[b].push_back({a, c});
  21.     }
  22.    
  23.    
  24.     int S, E;
  25.     cin >> S >> E;
  26.    
  27.    
  28.     vector<bool> visited(n, false);
  29.     vector<int> dist(n, INF);
  30.    
  31.     dist[S] = 0;
  32.    
  33.     priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
  34.     pq.push({S, 0});
  35.    
  36.    
  37.     while(!pq.empty()) {
  38.         pair<int, int> node = pq.top();
  39.         pq.pop();
  40.        
  41.         int c_node = node.first;
  42.         int c_shortest_path = node.second;
  43.        
  44.         if(visited[c_node]) continue;
  45.         visited[c_node] = true;
  46.        
  47.        
  48.        
  49.         for(pair<int, int> neighbour: graph[c_node]) {
  50.             if(!visited[neighbour.first] and neighbour.second + c_shortest_path < dist[neighbour.first]) {
  51.                 dist[neighbour.first] = neighbour.second + c_shortest_path;
  52.                 pq.push({neighbour.first, dist[neighbour.first]});
  53.             }
  54.         }
  55.        
  56.        
  57.     }
  58.  
  59.    
  60.     for(int i = 0; i < n; i++) {
  61.         cout << i << " " << dist[i] << endl;
  62.     }
  63.      return 0;
  64. }
  65. /*
  66.  5 6
  67.  0 1 19
  68.  0 2 14
  69.  1 2 20
  70.  2 3 10
  71.  3 4 13
  72.  2 4 100
  73.  0 4
  74.  **/
  75.  
Advertisement
Add Comment
Please, Sign In to add comment