Advertisement
Josif_tepe

Untitled

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