fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3.  
  4. /*
  5.  
  6. 7
  7. 6
  8. 1 2
  9. 1 3
  10. 2 4
  11. 2 5
  12. 3 6
  13. 3 7
  14.  
  15. case 2:-
  16. 2
  17. 1
  18. 1 2
  19.  
  20. cas 3:-
  21. 1
  22. 0
  23.  
  24. */
  25.  
  26.  
  27. import java.util.*;
  28. import java.lang.*;
  29. import java.io.*;
  30.  
  31. /* Name of the class has to be "Main" only if the class is public. */
  32. class Ideone
  33. {
  34. public static void main (String[] args) throws java.lang.Exception
  35. {
  36. Scanner sc = new Scanner(System.in);
  37. int n = sc.nextInt();
  38. int m = sc.nextInt();
  39. List<List<Integer>> adj = new ArrayList<>();
  40. for(int i=0; i<=n;i++){
  41. adj.add(new ArrayList<>());
  42. }
  43. int[] val = new int[adj.size()];
  44.  
  45. for(int i=1;i<val.length;i++){
  46. val[i] = sc.nextInt();
  47. }
  48.  
  49. for(int i=0; i<m; i++){
  50. int u = sc.nextInt();
  51. int v = sc.nextInt();
  52. adj.get(u).add(v);
  53. adj.get(v).add(u);
  54. }
  55.  
  56. int []ans = countTheNumberOf1(adj,1,val);
  57. System.out.println(Arrays.toString(ans));
  58.  
  59. }
  60.  
  61. public static int[] countTheNumberOf1(List<List<Integer>> adj,int src,int []val){
  62.  
  63. Queue<Integer> q = new LinkedList<>();
  64. boolean visited[] = new boolean[adj.size()];
  65. q.add(src);
  66. visited[src] = true;
  67. int[] ans = new int[val.length];
  68.  
  69. ans[src] = val[src];
  70. while(!q.isEmpty()){
  71. int cur = q.poll();
  72. for(int x : adj.get(cur)){
  73. if(!visited[x]){
  74. q.add(x);
  75. visited[x] = true;
  76. if(val[x] == 1){
  77. ans[x]= ans[cur]+1;
  78. }else{
  79. ans[x]=ans[cur];
  80. }
  81. }
  82. }
  83. }
  84.  
  85. return ans;
  86.  
  87. }
  88.  
  89. }
Success #stdin #stdout 0.12s 56560KB
stdin
7
6
0
1
0
1
1
1
0
1 2
1 3
2 4
2 5
3 6
3 7
stdout
[0, 0, 1, 0, 2, 2, 1, 0]