Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- struct Node{
- int height;
- int par;
- bool child;
- Node():height(0), par(-1), child(false){};
- };
- int main(){
- int n;
- int x, y;
- vector<Node*> nodes;
- vector<int> leaf;
- cin>>n;
- for(int i = 1 ; i <= n ; i++){
- nodes.push_back(new Node());
- }
- nodes[0]->par = -2;
- for(int i = 1 ; i < n ; i++){
- cin>>x>>y;
- if(nodes[x-1]->par == -1){
- nodes[x-1]->par = y-1;
- nodes[y-1]->child = true;
- }
- else if(nodes[y-1]->par == -1){
- nodes[y-1]->par = x-1;
- nodes[x-1]->child = true;
- }
- }
- for(int i = 0 ; i < n ; i++){
- if(nodes[i]->child == false)
- leaf.push_back(i);
- }
- for(int i = 0 ; i < (int)leaf.size() ; i++){
- int cur = leaf[i];
- int h = 0;
- while(cur != -2){
- nodes[cur]->height = max(nodes[cur]->height, h);
- cur = nodes[cur]->par;
- h++;
- }
- }
- for(int i = 0 ; i < n ; i++){
- cout<<nodes[i]->height<<" "<<nodes[i]->par+1<<"\n";
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement