Advertisement
josiftepe

Untitled

Jan 4th, 2023
1,211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. using namespace std;
  5. struct node {
  6.     int idx, cost;
  7.     node () {}
  8.     node(int _idx, int _cost) {
  9.         idx = _idx;
  10.         cost = _cost;
  11.     }
  12.     bool operator < (const node &tmp) const {
  13.         if(cost == tmp.cost) {
  14.             return idx < tmp.idx;
  15.         }
  16.         return cost > tmp.cost;
  17.     }
  18. };
  19. int main() {
  20.     int n, m;
  21.     cin >> n >> m;
  22.     vector<int> g[n];
  23.    
  24.     for(int i = 0; i < m; i++) {
  25.         int a, b;
  26.         cin >> a >> b;
  27.         g[a].push_back(b);
  28.         g[b].push_back(a);
  29.     }
  30.     priority_queue<node> pq;
  31.     int S; // starting node
  32.     cin >> S;
  33.     int E;
  34.     cin >> E; // ending node
  35.     bool visited[n];
  36.     for(int i = 0; i < n; i++) {
  37.         visited[i] = false;
  38.     }
  39.     pq.push(node(S, 0));
  40.     int path[n];
  41.     while (!pq.empty()) {
  42.         node c = pq.top();
  43.         pq.pop();
  44.         if(c.idx == E) {
  45.             break;
  46.         }
  47.         visited[c.idx] = true;
  48.         for(int i = 0; i < g[c.idx].size(); i++) {
  49.             int neighbour = g[c.idx][i];
  50.             if(!visited[neighbour]) {
  51.                 pq.push(node(neighbour, c.cost + 1));
  52.                 path[neighbour] = c.idx;
  53.             }
  54.         }
  55.     }
  56.     while(E != S) {
  57.         cout << path[E] << " ";
  58.         E = path[E];
  59.     }
  60.     return 0;
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement