Advertisement
Guest User

Finding Center of TREE

a guest
Apr 25th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define ll long long
  4. #define io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
  5. const int MAX = 1e6 + 5;
  6. vector <int> a[MAX];
  7. queue <int> q;
  8. int used[MAX], n, ln[MAX], lm[MAX], x;
  9.  
  10. void zero(int n){
  11.     for(int i = 1; i <= n; i++){
  12.         ln[i] = 0;
  13.         used[i] = 0;
  14.     }
  15. }
  16.  
  17. void BFS(int node){
  18.     q.push(node);
  19.     used[node] = 1;
  20.     while(!q.empty()){
  21.         int s = q.front();
  22.         q.pop();
  23.         for(int i : a[s]){
  24.             if(!used[i]){
  25.                 q.push(i);
  26.                 used[i] = 1;
  27.                 ln[i] = ln[s] + 1;
  28.             }
  29.         }
  30.     }
  31. }
  32.  
  33. int main(){
  34.     io;
  35.     cin >> n;
  36.     if(n == 1){
  37.         cout << 1;
  38.         return 0;
  39.     }
  40.     for(int i = 2; i <= n; i++){
  41.         cin >> x;
  42.         a[x].push_back(i);
  43.         a[i].push_back(x);
  44.     }
  45.     BFS(1);
  46.     int d = 0, d1, d2;
  47.     for(int i = 1; i <= n; i++){
  48.         if(ln[i] > d){
  49.             d = ln[i];
  50.             d1 = i;
  51.         }
  52.     }
  53.     d = 0;
  54.     zero(n);
  55.     BFS(d1);
  56.     for(int i = 1; i <= n; i++){
  57.         lm[i] = ln[i];
  58.         if(ln[i] > d){
  59.             d = ln[i];
  60.             d2 = i;
  61.         }
  62.     }
  63.     zero(n);
  64.     BFS(d2);
  65.     int r1 = d / 2;
  66.     int r2 = d / 2;
  67.     if(d % 2 == 1){
  68.         r2++;
  69.     }
  70.     for(int i = 1; i <= n; i++){
  71.         if(ln[i] == r1 && lm[i] == r2){
  72.             cout << i << " ";
  73.         }
  74.         else if(ln[i] == r2 && lm[i] == r1){
  75.             cout << i << " ";
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement