Advertisement
josiftepe

Untitled

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