fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. static void dfs(int node,List<List<Integer>> adj, int visited[], int parent[], int height[])
  11. {
  12. visited[node]=1;
  13. for(int ele:adj.get(node))
  14. {
  15. if(visited[ele]==0)
  16. {
  17. parent[ele]=node;
  18. dfs(ele,adj,visited,parent,height);
  19. }
  20. }
  21.  
  22.  
  23. int h=0;
  24. for(int ele:adj.get(node))
  25. {
  26. if(ele!=parent[node])
  27. {
  28. h=Math.max(h,height[ele]);
  29. }
  30. }
  31. height[node]=h+1;
  32. }
  33. public static void main (String[] args) throws java.lang.Exception
  34. {
  35. // your code goes here
  36. Scanner sc=new Scanner(System.in);
  37. int n=sc.nextInt();
  38. List<List<Integer>> adj=new ArrayList<>();
  39. int height[]=new int[n+1];
  40. int parent[]=new int[n+1];
  41. int visited[]=new int[n+1];
  42.  
  43. for(int i=0;i<=n;i++)
  44. adj.add(new ArrayList<>());
  45.  
  46.  
  47. for(int i=1;i<n;i++)
  48. {
  49. int u=sc.nextInt();
  50. int v=sc.nextInt();
  51. adj.get(u).add(v);
  52. adj.get(v).add(u);
  53.  
  54. }
  55.  
  56. dfs(1,adj,visited,parent,height);
  57.  
  58. for(int i=1;i<=n;i++)
  59. System.out.print(height[i]+" ");
  60.  
  61. }
  62. }
Success #stdin #stdout 0.15s 58964KB
stdin
5
1 2
2 3 
3 4 
1 5 
stdout
4 3 2 1 1