fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. static long[] height;
  5.  
  6. public static void DFS(int node, List<Integer>[] G, int[] used, int[] parent) {
  7. used[node] = 1;
  8.  
  9. for (int u : G[node]) {
  10. if (used[u] == 0) {
  11. parent[u] = node;
  12. DFS(u, G, used, parent);
  13. }
  14. }
  15.  
  16. long h = 0;
  17. for (int child : G[node]) {
  18. if (child == parent[node]) continue;
  19. h = Math.max(h, height[child]);
  20. }
  21.  
  22. height[node] = 1 + h;
  23. }
  24.  
  25. public static void main(String[] args) {
  26. Scanner scanner = new Scanner(System.in);
  27. int n = scanner.nextInt();
  28. height = new long[n + 1];
  29.  
  30. List<Integer>[] G = new List[n + 1];
  31. for (int i = 0; i <= n; i++) {
  32. G[i] = new ArrayList<>();
  33. }
  34.  
  35. for (int i = 1; i <= n - 1; i++) {
  36. int u = scanner.nextInt();
  37. int v = scanner.nextInt();
  38. G[u].add(v);
  39. G[v].add(u);
  40. }
  41.  
  42. int[] used = new int[n + 1];
  43. int[] parent = new int[n + 1];
  44. DFS(1, G, used, parent);
  45.  
  46. for (int i = 1; i <= n; i++) {
  47. System.out.println(height[i]);
  48. }
  49. }
  50. }
  51.  
Success #stdin #stdout 0.12s 54588KB
stdin
5
1 2
1 3
2 4
2 5
stdout
3
2
1
1
1