nq1s788

бфс

Mar 7th, 2026
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.85 KB | None | 0 0
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <map>
  4. #include <vector>
  5. #include <algorithm>
  6. #include <unordered_set>
  7. #include <set>
  8. #include <deque>
  9.  
  10. using namespace std;
  11.  
  12. int main() {
  13.     int n, m;
  14.     cin >> n >> m;
  15.     vector<vector<int>> g(n);
  16.     for (int i = 0; i < m; i++) {
  17.         int x, y;
  18.         cin >> x >> y;
  19.         x--, y--;
  20.         g[x].push_back(y);
  21.         g[y].push_back(x);
  22.     }
  23.     int start;
  24.     cin >> start;
  25.     start--;
  26.     vector<int> rst(n, -1);
  27.     rst[start] = 0;
  28.     deque<int> q;
  29.     q.push_back(start);
  30.     while (!q.empty()) {
  31.         int h = q.front();
  32.         q.pop_front();
  33.         for (auto e : g[h]) {
  34.             if (rst[e] == -1) {
  35.                 rst[e] = rst[h] + 1;
  36.                 q.push_back(e);
  37.             }
  38.         }
  39.     }
  40.     for (auto e : rst) cout << e << ' ';
  41.  
  42.     return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment