Advertisement
Josif_tepe

Untitled

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