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