fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long int ll ;
  4. ll height[1000];
  5. int b[1000];
  6. void dfs(int node,vector <int> g[],int used[],int par[]){
  7. used[node]=1;
  8. for(auto u:g[node]){
  9. if(used[u]==0){
  10. par[u]=node;
  11. dfs(u,g,used,par);
  12. }
  13. }
  14. ll h=0;
  15. for(auto c:g[node]){
  16. if(c==par[node]){
  17. // parent so dont count as height
  18. }
  19. h = max(h,height[c]);
  20.  
  21. }
  22. height[node]=1+h;
  23. }
  24.  
  25. int main(){
  26. int n ;
  27. cin>>n ;
  28. vector<int> g[n+1];
  29. int i=1;
  30. while(i<=n){
  31. int u,v;
  32. cin>>u>>v;
  33. g[u].push_back(v);
  34. g[v].push_back(u);
  35. i++;
  36. }
  37. int used[n+1]={0};
  38. int par[n+1]={0};
  39. dfs(1,g,used, par);
  40. i=1;
  41. while(i<=n){
  42. cout<<height[i]<<"\n";
  43. i++;
  44. }
  45. }
  46.  
  47.  
Success #stdin #stdout 0s 5284KB
stdin
5
1 2
2 3 
3 4 
1 5 
stdout
4
3
2
1
1