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. int[] arr = new int[n + 1];
  9. List<Integer>[] g = new ArrayList[n + 1];
  10. for (int i = 1; i <= n; i++) g[i] = new ArrayList<>();
  11.  
  12. for (int i = 0; i < n - 1; i++) {
  13. int u = sc.nextInt(), v = sc.nextInt();
  14. g[u].add(v);
  15. g[v].add(u);
  16. }
  17.  
  18. for (int i = 1; i <= n; i++) arr[i] = sc.nextInt();
  19.  
  20. int[] ans = new int[n + 1];
  21. boolean[] vis = new boolean[n + 1];
  22. Queue<Integer> q = new LinkedList<>();
  23.  
  24. vis[1] = true;
  25. ans[1] = arr[1];
  26. q.add(1);
  27.  
  28. while (!q.isEmpty()) {
  29. int node = q.poll();
  30. for (int w : g[node]) {
  31. if (!vis[w]) {
  32. vis[w] = true;
  33. ans[w] = ans[node] + (arr[w] == 1 ? 1 : 0);
  34. q.add(w);
  35. }
  36. }
  37. }
  38.  
  39. for (int i = 1; i <= n; i++) {
  40. System.out.println(ans[i]);
  41. }
  42. }
  43. }
  44.  
Success #stdin #stdout 0.14s 54624KB
stdin
5
1 2
2 3 
3 4 
4 5 
1 0 0 1 1 1
stdout
1
1
1
2
3