Advertisement
Josif_tepe

Untitled

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