Josif_tepe

Untitled

Aug 20th, 2025
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #include <algorithm>
  5. using namespace std;
  6. const int maxn = 1e5 + 5;
  7. int k;
  8. vector<int> graph[maxn];
  9.  
  10. void bfs(int S, bool to_reverse) {
  11.     queue<int> q;
  12.     q.push(S);
  13.    
  14.     vector<bool> visited(k + 1, false);
  15.     vector<int> path;
  16.     path.push_back(S);
  17.     visited[S] = true;
  18.     while(!q.empty()) {
  19.         int current_node = q.front();
  20.         q.pop();
  21.        
  22.        
  23.         for(int neighbour : graph[current_node]) {
  24.             if(!visited[neighbour]) {
  25.                 path.push_back(neighbour);
  26.                 visited[neighbour] = true;
  27.                 q.push(neighbour);
  28.             }
  29.         }
  30.     }
  31.    
  32.     if(to_reverse) {
  33.         reverse(path.begin(), path.end());
  34.     }
  35.    
  36.     for(int node: path) {
  37.         cout << node << " ";
  38.     }
  39.    
  40. }
  41. int main() {
  42.     ios_base::sync_with_stdio(false);
  43.     cin >> k;
  44.    
  45.     for(int i = 0; i < k - 1; i++) {
  46.         int a, b;
  47.         cin >> a >> b;
  48.         graph[a].push_back(b);
  49.         graph[b].push_back(a);
  50.     }
  51.  
  52.     bfs(0, false);
  53.     bfs(k, true);
  54.     return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment