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 int height[];
  11. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. // your code goes here
  14. Scanner sc=new Scanner(System.in);
  15. int n=sc.nextInt();
  16. height=new int[n+1];
  17. ArrayList<ArrayList<Integer>> adj=new ArrayList<>();
  18. for(int i=0;i<=n;i++){
  19. adj.add(new ArrayList<>());
  20.  
  21. }
  22. for(int i=0;i<n-1;i++){
  23. int x=sc.nextInt();
  24. int y=sc.nextInt();
  25. adj.get(x).add(y);
  26. adj.get(y).add(x);
  27. }
  28. int used[]=new int[n+1];
  29. int parent[]=new int [n+1];
  30. dfs(1,adj,used,parent);
  31. for(int i=1;i<=n;i++){
  32. System.out.println(i+ " "+ height[i]);
  33. }
  34. }
  35. public static void dfs(int node,ArrayList<ArrayList<Integer>> adj,int used[],int parent[]){
  36.  
  37. used[node]=1;
  38. for(int x: adj.get(node)){
  39. if(used[x]==0){
  40. parent[x]=node;
  41. dfs(x,adj,used,parent);
  42. }
  43. }
  44. int h=0;
  45. for(int x: adj.get(node)){
  46. if(parent[node]==x){
  47. continue;
  48. }
  49. else{
  50. h=Math.max(h,height[x]);
  51. }
  52.  
  53. }
  54. height[node]=h+1;
  55. }
  56. }
Success #stdin #stdout 0.14s 21788KB
stdin
5
1
2
1
5
1
3
3
4
stdout
1 3
2 1
3 2
4 1
5 1