Advertisement
tepyotin2

Find the Father

May 11th, 2025
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int n;
  6. vector<int> adj[100001];
  7. queue<int> q;
  8. bool visited[100001];
  9. int father[100001];
  10.  
  11. int main(){
  12.     //freopen("father.in", "r", stdin);
  13.    
  14.     cin >> n;
  15.     int a, b;
  16.     while(cin >> a){
  17.         cin >> b;
  18.         adj[a].push_back(b);
  19.         adj[b].push_back(a);
  20.         //cout << a << " " << b << '\n';
  21.     }
  22.     for(int i=1; i<=n; i++){
  23.         sort(adj[i].begin(), adj[i].end());
  24.     }
  25.     q.push(1);
  26.     visited[1] = true;
  27.     while(!q.empty()){
  28.         int cur = q.front();
  29.         q.pop();
  30.         for(auto v: adj[cur]){
  31.             if(!visited[v]){
  32.                 visited[v] = true;
  33.                 father[v] = cur;
  34.                 q.push(v);
  35.             }
  36.         }
  37.     }
  38.     for(int i=2; i<=n; i++){
  39.         cout << father[i] << '\n';
  40.     }
  41.    
  42.     return 0;
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement