Advertisement
smatskevich

Lesson27

Apr 11th, 2024
736
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4.  
  5. #define all(x) x.begin(), x.end()
  6. using namespace std;
  7.  
  8. void BFS(int s, vector<vector<int>>& g, vector<int>& r, vector<int>& pi) {
  9.   int n = r.size();
  10.   queue<int> q;
  11.   q.push(s);
  12.   r[s] = 0;
  13.   while (!q.empty()) {
  14.     int u = q.front(); q.pop();
  15.     for (int v : g[u]) {
  16.       if (r[v] == INT_MAX) {
  17.         r[v] = r[u] + 1;
  18.         pi[v] = u;
  19.         q.push(v);
  20.       }
  21.     }
  22.   }
  23. }
  24.  
  25. int main() {
  26.   int n, m; cin >> n >> m;
  27.   vector<vector<int>> g(n);
  28. //  for (int i = 0; i < m; ++i)
  29.   while (m--) {
  30.     int u, v; cin >> u >> v;  --u; --v;
  31.     g[u].push_back(v);
  32.     g[v].push_back(u);
  33.   }
  34.   int s; cin >> s; --s;
  35.   vector<int> r(n, INT_MAX), pi(n, -1);
  36.   BFS(s, g, r, pi);
  37.  
  38.   for (int u = 0; u < n; ++u) {
  39.     cout << "Vertex " << u + 1 << ": dist = " << r[u] << ", path = [";
  40.     vector<int> path;
  41.     for (int v = u; v != -1; v = pi[v]) path.push_back(v);
  42.     reverse(all(path));
  43.     for (int v : path) cout << v + 1 << (v == u ? "]\n" : ", ");
  44.   }
  45.   return 0;
  46. }
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement