Advertisement
Josif_tepe

Untitled

May 11th, 2021
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <cmath>
  4. #include <algorithm>
  5. #include <vector>
  6. using namespace std;
  7.  
  8.  
  9. struct node {
  10.     int idx;
  11.     int distance;
  12.    
  13.     node() {}
  14.     node(int _idx, int _distance) {
  15.         idx = _idx;
  16.         distance = _distance;
  17.     }
  18.    
  19.     bool operator < (const node &tmp) const {
  20.         return distance > tmp.distance;
  21.     }
  22.    
  23. };
  24. int main() {
  25.     int n; // broj na teminja
  26.     int m; // brojot na rebra
  27.     cin >> n >> m;
  28.    
  29.     vector<pair<int, int> > graph[n + 1];
  30.     for(int i = 0; i < m; i++) {
  31.         int a, b, c; // povrzani se teminjata a i b so distanca c
  32.         cin >> a >> b >> c;
  33.         graph[a].push_back(make_pair(b, c));
  34.         graph[b].push_back(make_pair(a, c));
  35.     }
  36.    
  37.     int S, E;
  38.     // S --> pocetno teme
  39.     // E --> krajno teme
  40.     cin >> S >> E;
  41.    
  42.     priority_queue<node> pq;
  43.     pq.push(node(S, 0)); // prviot element vo priority queue
  44.    
  45.     bool visited[n + 1];
  46.     for(int i = 0; i < n; i++) {
  47.         visited[i] = false;
  48.     }
  49.    
  50.     while(!pq.empty()) {
  51.         node c = pq.top();
  52.         pq.pop();
  53.        
  54.         visited[c.idx] = true;
  55.         if(c.idx == E) {
  56.             cout << c.distance << endl;
  57.             break;
  58.         }
  59.         for(int i = 0; i < graph[c.idx].size(); i++) {
  60.             int sosed = graph[c.idx][i].first;
  61.             int rebro = graph[c.idx][i].second;
  62.             if(!visited[sosed]) {
  63.                 pq.push(node(sosed, c.distance + rebro));
  64.             }
  65.         }
  66.     }
  67.    
  68.     return 0;
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement