Advertisement
Georgiy031

Untitled

Apr 14th, 2020
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.74 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4.  
  5. using namespace std;
  6.  
  7. void bfs(int r, vector<bool>& used, vector<vector<int>>& g, vector<int>& way) {
  8.     queue<int> q;
  9.     q.push(r);
  10.     used[r] = true;
  11.     while (!q.empty()) {
  12.         int v = q.front();
  13.         q.pop();
  14.         way.push_back(v);
  15.         for (int i = 0; i < g[v].size(); ++i) {
  16.             int to = g[v][i];
  17.             if (used[to] == false) {
  18.                 used[to] = true;
  19.                 q.push(to);
  20.             }
  21.         }
  22.     }
  23. }
  24. int main() {
  25.     int n, m, r;
  26.     cin >> n >> m >> r;
  27.     vector<vector<int>> g(n);
  28.     vector<bool> used(n, false);
  29.     vector<int> way;
  30.     for (int i = 0; i < m; ++i) {
  31.         int a, b;
  32.         cin >> a >> b;
  33.         --a, --b;
  34.         g[a].push_back(b);
  35.         g[b].push_back(a);
  36.     }
  37.     bfs(r - 1, used, g, way);
  38.     cout << way.size() << endl;
  39.     for (auto x : way) cout << x + 1 << " ";
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement