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. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. Scanner in = new Scanner(System.in);
  14. int n = in.nextInt();
  15.  
  16. int arr[] = new int[n+1];
  17.  
  18. List<Integer>[] G = new ArrayList[n+1];
  19. for(int i =1;i<=n;i++){
  20. G[i] = new ArrayList<>();
  21. }
  22.  
  23. int i = 1;
  24. while(i<=n-1){
  25. int x = in.nextInt();
  26. int y = in.nextInt();
  27. G[x].add(y);
  28. G[y].add(x);
  29. i++;
  30. }
  31.  
  32. i =1;
  33. while(i<=n){
  34. arr[i] = in.nextInt();
  35. i++;
  36. }
  37.  
  38. Queue<Integer> q = new LinkedList<>();
  39. int[] used = new int[n+1];
  40. used[1] = 1;
  41. q.add(1);
  42. int[] answer = new int[n+1];
  43. answer[1] = arr[1];
  44.  
  45. while(!q.isEmpty()){
  46. int top = q.poll();
  47. int c =0;
  48.  
  49. for(int u:G[top]){
  50. if(used[u] == 0){
  51. c++;
  52. used[u] =1;
  53. q.add(u);
  54.  
  55. if(arr[u] == 1){
  56. answer[u] = answer[top] +1;
  57. }
  58. else{
  59. answer[u] = answer[top];
  60. }
  61. }
  62. }
  63. }
  64.  
  65. i =1;
  66. while(i<=n){
  67. System.out.println(answer[i]);
  68. i++;
  69. }
  70. }
  71. }
Success #stdin #stdout 0.18s 56564KB
stdin
5
1 2
2 3
3 4
4 5
1 0 0 1 1 1
stdout
1
1
1
2
3