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 Codechef
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13. Scanner scanner = new Scanner(System.in);
  14.  
  15. int n = scanner.nextInt();
  16. int m = scanner.nextInt();
  17.  
  18. List<Integer>[] adj = new ArrayList[n + 1];
  19. for (int i = 0; i <= n; i++) {
  20. adj[i] = new ArrayList<>();
  21. }
  22.  
  23. int[] val = new int[n + 1];
  24.  
  25. for (int i = 1; i <= n; i++) {
  26. val[i] = scanner.nextInt();
  27. }
  28. for (int i = 0; i < m; i++) {
  29. int u = scanner.nextInt();
  30. int v = scanner.nextInt();
  31. adj[u].add(v);
  32. adj[v].add(u);
  33. }
  34. scanner.close();
  35.  
  36. solve(n,adj,val);
  37.  
  38.  
  39. }
  40. public static void solve(int n, List<Integer>[] adj, int[] val) {
  41. int[] used = new int[n+1];
  42.  
  43. int[] max5 = new int[n+1];
  44. int[] lvl=new int[n+1];
  45. int[] countP=new int[n+1];
  46.  
  47. Queue<Integer> queue = new LinkedList<>();
  48.  
  49. if(val[1]==5){
  50. max5[1]=1;
  51. }
  52. queue.add(1);
  53. used[1]=1;
  54. lvl[1]=0;
  55. countP[1]=1;
  56.  
  57. while (!queue.isEmpty()) {
  58. int u = queue.poll();
  59.  
  60. for (int v : adj[u]) {
  61. int vFives=0;
  62. if(val[v]==5){
  63. vFives=1;
  64. }
  65. if (used[v] == 0) {
  66. lvl[v]=lvl[u]+1;
  67. used[v] = 1;
  68. countP[v] = countP[u];
  69. max5[v] = max5[u] + vFives;
  70. queue.add(v);
  71. countP[v] = countP[u];
  72. }
  73. else{
  74. if(lvl[v]==lvl[u]+1){
  75. int fre5=max5[u]+vFives;
  76. max5[v]=Math.max(max5[v],fre5);
  77. countP[v] += countP[u];
  78. }
  79. }
  80. }
  81. }
  82.  
  83. for (int i = 1; i <= n; i++) {
  84. System.out.println("Node " + i + " : " + " maxFives=" + max5[i] +" with distance of "+lvl[i] +" with count of :"+countP[i]);
  85. }
  86. }
  87. }
Success #stdin #stdout 0.22s 61068KB
stdin
5 4
5 5 0 5 0
1 2
2 5
1 3
3 5
stdout
Node 1 :  maxFives=1 with distance of 0 with count of :1
Node 2 :  maxFives=2 with distance of 1 with count of :1
Node 3 :  maxFives=1 with distance of 1 with count of :1
Node 4 :  maxFives=0 with distance of 0 with count of :0
Node 5 :  maxFives=2 with distance of 2 with count of :2