Advertisement
Josif_tepe

Untitled

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