Advertisement
Josif_tepe

Untitled

Sep 13th, 2021
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4.  
  5. using namespace std;
  6. /*
  7.  0: (1, 2)
  8.  1:
  9.  2:
  10.  3:
  11.  4:
  12.  
  13.  
  14.  **/
  15.  
  16. struct node {
  17.     int index, shortest_cost;
  18.    
  19.     node(int i, int s) {
  20.         index = i;
  21.         shortest_cost = s;
  22.     }
  23.    
  24.     bool operator < (const node &tmp) const {
  25.         return shortest_cost > tmp.shortest_cost;
  26.     }
  27. };
  28.  
  29. int main()
  30. {
  31.     int n, m; // broj na teminja, broj na rebra
  32.     cin >> n >> m;
  33.     vector<pair<int, int> > graph[n + 5];
  34.     for(int i = 0; i < m; i++) {
  35.         int a, b, c; // temeto A e povrzano so temeto B i odaleceni se so C
  36.         cin >> a >> b >> c;
  37.         graph[a].push_back(make_pair(b, c));
  38.         graph[b].push_back(make_pair(a, c));
  39.     }
  40.    
  41.     int S, E;
  42.     cin >> S >> E;
  43.     // od kade sakam do kade sakam da najdam najkratok pat
  44.     priority_queue<node> pq;
  45.     pq.push(node(S, 0));
  46.    
  47.     vector<bool> visited(n + 1, false);
  48.     vector<int> distance(n + 1, 2e9);
  49.     distance[S] = 0;
  50.    
  51.     while(!pq.empty()) {
  52.         node current = pq.top(); // kazi mi koj e najmal sosed
  53.         pq.pop();
  54.        
  55.         visited[current.index] = true;
  56.         if(current.index == E) {
  57.             cout << current.shortest_cost << endl; // ova e najkratkiot pat
  58.             break;
  59.         }
  60.        
  61.         for(int i = 0; i < graph[current.index].size(); i++) {
  62.             int sosed = graph[current.index][i].first;
  63.             int pat = graph[current.index][i].second;
  64.            
  65.             if(!visited[sosed] and current.shortest_cost + pat < distance[sosed]) {
  66.                 pq.push(node(sosed, current.shortest_cost + pat));
  67.                 distance[sosed] = current.shortest_cost + pat;
  68.             }
  69.            
  70.         }
  71.     }
  72.     for(int i = 1; i <= n; i++) {
  73.         cout << S << " " << i << " " << distance[i] << endl;
  74.     }
  75.     return 0;
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement