fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define ll long long
  5.  
  6. ll height[1000000];
  7.  
  8. void dfs(int node,vector<int>t[],vector<int>v,vector<int>parent){
  9. v[node]=1;
  10. for(auto it:t[node]){
  11. if(v[it]==0){
  12. parent[it]=node;
  13. dfs(it,t,v,parent);
  14. }
  15. }
  16. ll h=0;
  17. for(auto child:t[node]){
  18. if(child!=parent[node])h=max(h,height[child]);
  19. }
  20. height[node]=h+1;
  21. }
  22.  
  23. int main(){
  24. ios_base::sync_with_stdio(false);
  25. cin.tie(NULL);
  26. int n;
  27. cin>>n;
  28. vector<int>t[n+1],value(n+1);
  29. for(int i=1;i<n;i++){
  30. int x,y;
  31. cin>>x>>y;
  32. t[x].push_back(y);
  33. t[y].push_back(x);
  34. }
  35. vector<int>v(n+1),parent(n+1);
  36. dfs(1,t,v,parent);
  37. for(int i=1;i<=n;i++)cout<<height[i]<<" ";
  38. return 0;
  39. }
Success #stdin #stdout 0.01s 5320KB
stdin
5
1 2
2 3 
3 4 
1 5
stdout
4 3 2 1 1