Advertisement
KuanTall

Untitled

Nov 22nd, 2022
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | Food | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct Node{
  6.     int height;
  7.     int par;
  8.     bool child;
  9.  
  10.     Node():height(0), par(-1), child(false){};
  11. };
  12.  
  13. int main(){
  14.     int n;
  15.     int x, y;
  16.     vector<Node*> nodes;
  17.     vector<int> leaf;
  18.     cin>>n;
  19.     for(int i = 1 ; i <= n ; i++){
  20.         nodes.push_back(new Node());
  21.     }
  22.     nodes[0]->par = -2;
  23.     for(int i = 1 ; i < n ; i++){
  24.         cin>>x>>y;
  25.         if(nodes[x-1]->par == -1){
  26.             nodes[x-1]->par = y-1;
  27.             nodes[y-1]->child = true;
  28.         }
  29.         else if(nodes[y-1]->par == -1){
  30.             nodes[y-1]->par = x-1;
  31.             nodes[x-1]->child = true;
  32.         }
  33.     }
  34.     for(int i = 0 ; i < n ; i++){
  35.         if(nodes[i]->child == false)
  36.             leaf.push_back(i);
  37.     }
  38.     for(int i = 0 ; i < (int)leaf.size() ; i++){
  39.         int cur = leaf[i];
  40.         int h = 0;
  41.         while(cur != -2){
  42.             nodes[cur]->height = max(nodes[cur]->height, h);
  43.             cur = nodes[cur]->par;
  44.             h++;
  45.         }
  46.     }
  47.     for(int i = 0 ; i < n ; i++){
  48.         cout<<nodes[i]->height<<" "<<nodes[i]->par+1<<"\n";
  49.     }
  50.  
  51.     return 0;
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement