fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. Scanner scanner = new Scanner(System.in);
  6. int n = scanner.nextInt();
  7. ArrayList<Integer>[] G = new ArrayList[n + 1];
  8. for (int i = 1; i <= n; i++) {
  9. G[i] = new ArrayList<>();
  10. }
  11.  
  12. int i = 1;
  13. while (i <= n - 1) {
  14. int x = scanner.nextInt();
  15. int y = scanner.nextInt();
  16. G[x].add(y);
  17. G[y].add(x);
  18. i++;
  19. }
  20. Queue<Integer> q = new LinkedList<>();
  21. int[] used = new int[n + 1];
  22. used[1] = 1;
  23. q.offer(1);
  24. while (!q.isEmpty()) {
  25. int node = q.poll();
  26. int c = 0;
  27. for (int u : G[node]) {
  28. if (used[u] == 0) {
  29. c++;
  30. used[u] = 1;
  31. q.offer(u);
  32. }
  33. }
  34. System.out.println(node + " " + c);
  35. }
  36. }
  37. }
Success #stdin #stdout 0.19s 60920KB
stdin
5
1 2
1 3
3 4
3 5
stdout
1 2
2 0
3 2
4 0
5 0