IvetValcheva

Untitled

Oct 3rd, 2022
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. package advanced.regular;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.util.Arrays;
  7. import java.util.Comparator;
  8. import java.util.PriorityQueue;
  9.  
  10. public class Creep {
  11. public static void main(String[] args) throws IOException {
  12. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  13.  
  14. int nodes = Integer.parseInt(reader.readLine());
  15. int edges = Integer.parseInt(reader.readLine());
  16.  
  17. int[][] graph = new int[nodes][nodes];
  18.  
  19. for (int i = 0; i < edges; i++) {
  20. int[] tokens = Arrays.stream(reader.readLine().split("\\s+"))
  21. .mapToInt(Integer::parseInt)
  22. .toArray();
  23.  
  24. int source = tokens[0];
  25. int destination = tokens[1];
  26. int weight = tokens[2];
  27.  
  28. graph[source][destination] = weight;
  29. }
  30.  
  31. int cost = 0;
  32.  
  33. int[] parents = new int[nodes];
  34.  
  35. for (int i = 0; i < nodes; i++) {
  36. parents[i] = i;
  37. }
  38.  
  39. PriorityQueue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt(n -> graph[n[0]][n[1]]));
  40.  
  41. for (int row = 0; row < graph.length; row++) {
  42. for (int col = 0; col < graph[row].length; col++) {
  43. if (graph[row][col] != 0) {
  44. queue.offer(new int[]{row, col});
  45. }
  46. }
  47. }
  48.  
  49. StringBuilder out = new StringBuilder();
  50.  
  51. while (!queue.isEmpty()) {
  52. int[] minEdge = queue.poll();
  53.  
  54. int from = minEdge[0];
  55. int to = minEdge[1];
  56. int weight = graph[from][to];
  57.  
  58. int firstRoot = findRoot(from, parents);
  59. int secondRoot = findRoot(to, parents);
  60.  
  61. if (firstRoot != secondRoot) {
  62. parents[secondRoot] = firstRoot;
  63. out.append(from).append(" ").append(to).append(System.lineSeparator());
  64. cost += weight;
  65. }
  66. }
  67.  
  68. out.append(cost);
  69.  
  70. System.out.println(out);
  71. }
  72.  
  73. private static int findRoot(int from, int[] parents) {
  74. while (parents[from] != from) {
  75. from = parents[from];
  76. }
  77. return from;
  78. }
  79. }
  80.  
Add Comment
Please, Sign In to add comment