| 15 | } |
| 16 | |
| 17 | class Kruskal { |
| 18 | |
| 19 | private int V; |
| 20 | private PriorityQueue<Edge> pq; |
| 21 | private int[] root; |
| 22 | |
| 23 | public Kruskal() { |
| 24 | pq = new PriorityQueue<>(((o1, o2) -> o1.c - o2.c)); |
| 25 | } |
| 26 | |
| 27 | public void setV(int v) { |
| 28 | V = v; |
| 29 | setRoot(); |
| 30 | } |
| 31 | |
| 32 | public void setEdges(int a, int b, int c) { |
| 33 | pq.offer(new Edge(a, b, c)); |
| 34 | } |
| 35 | |
| 36 | private void setRoot() { |
| 37 | root = new int[V+1]; |
| 38 | for (int i = 1; i <= V; i++) root[i] = i; |
| 39 | } |
| 40 | |
| 41 | public int getMSTCost() { |
| 42 | int cost = 0; |
| 43 | while (!pq.isEmpty()) { |
| 44 | Edge e = pq.poll(); |
| 45 | if (find(e.a) == find(e.b)) continue; |
| 46 | merge(e.a, e.b); |
| 47 | cost += e.c; |
| 48 | } |
| 49 | return cost; |
| 50 | } |
| 51 | |
| 52 | private int find(int n) { |
| 53 | if (root[n] == n) return n; |
| 54 | return root[n] = find(root[n]); |
| 55 | } |
| 56 | |
| 57 | private void merge(int a, int b) { |
| 58 | root[find(b)] = find(a); |
| 59 | } |
| 60 | |
| 61 | static class Edge { |
| 62 | int a, b, c; |
| 63 | |
| 64 | public Edge(int a, int b, int c) { |
| 65 | this.a = a; |
| 66 | this.b = b; |
| 67 | this.c = c; |
| 68 | } |
| 69 | } |
| 70 | } |
nothing calls this directly
no outgoing calls
no test coverage detected