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 sc=new Scanner(System.in);
  14. int n=sc.nextInt();
  15. List<List<Integer>> adj=new ArrayList<>();
  16. for(int i=0;i<=n;i++)
  17. adj.add(new ArrayList<>());
  18.  
  19. for(int i=1;i<n;i++)
  20. {
  21. int u=sc.nextInt();
  22. int v=sc.nextInt();
  23. adj.get(u).add(v);
  24. adj.get(v).add(u);
  25.  
  26.  
  27. }
  28.  
  29. int arr[]=new int[n+1];
  30. for(int i=1;i<=n;i++)
  31. arr[i]=sc.nextInt();
  32.  
  33.  
  34. Queue<Integer> q=new LinkedList<>();
  35. int visited[]=new int[n+1];
  36. int ans[]=new int[n+1];
  37.  
  38. q.add(1);
  39. visited[1]=1;
  40. ans[1]=arr[1];
  41.  
  42. while(!q.isEmpty())
  43. {
  44. int temp=q.poll();
  45. for(int ele:adj.get(temp))
  46. {
  47. if(visited[ele]==0)
  48. {
  49. q.add(ele);
  50. visited[ele]=1;
  51. if(arr[ele]==1)
  52. ans[ele]=ans[temp]+1;
  53. else
  54. ans[ele]=ans[temp];
  55. }
  56. }
  57. }
  58.  
  59. for(int i=1;i<=n;i++)
  60. System.out.print(ans[i]+" ");
  61.  
  62.  
  63. }
  64. }
Success #stdin #stdout 0.15s 59032KB
stdin
5
1 2
2 4
3 5
4 5 
1 0 1 1 1 1
stdout
1 1 4 2 3