Advertisement
Mirbek

Кратчайший путь

Jan 9th, 2022
1,052
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int N = 1e5 + 3;
  6.  
  7. int n, m;
  8. int used[N], dist[N], par[N];
  9. vector <int> g[N];
  10.  
  11. int main(){
  12.     cin >> n >> m;
  13.  
  14.     int start, finish;
  15.     cin >> start >> finish;
  16.  
  17.     for (int i = 1; i <= m; i++) {
  18.         int a, b;
  19.         cin >> a >> b;
  20.         g[a].push_back(b);
  21.         g[b].push_back(a);
  22.     }
  23.  
  24.     for (int i = 1; i <= n; i++) {
  25.         dist[i] = -1;
  26.     }
  27.  
  28.     queue <int> q;
  29.     dist[start] = 0;
  30.     used[start] = 1;
  31.     q.push(start);
  32.  
  33.     while (!q.empty()) {
  34.         int v = q.front();
  35.         q.pop();
  36.         for (int i = 0; i < g[v].size(); i++) {
  37.             int to = g[v][i];
  38.             if (!used[to]) {
  39.                 used[to] = 1;
  40.                 dist[to] = dist[v] + 1;
  41.                 par[to] = v;
  42.                 q.push(to);
  43.             }
  44.         }
  45.     }
  46.  
  47.     if (dist[finish] == -1) {
  48.         cout << -1 << endl;
  49.         return 0;
  50.     }
  51.  
  52.     cout << dist[finish] << endl;
  53.  
  54.     vector <int> path;
  55.     int x = finish;
  56.  
  57.     while (x > 0) {
  58.         path.push_back(x);
  59.         x = par[x];
  60.     }
  61.  
  62.     reverse(path.begin(), path.end());
  63.  
  64.     for (int x : path) {
  65.         cout << x << " ";
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement