|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int[] parent; |
| 7 | + |
| 8 | + public static void main(String[] args) throws IOException { |
| 9 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 10 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 11 | + int V = Integer.parseInt(st.nextToken()); |
| 12 | + int E = Integer.parseInt(st.nextToken()); |
| 13 | + |
| 14 | + List<Edge> edgeList = new ArrayList<>(); |
| 15 | + parent = new int[V + 1]; |
| 16 | + |
| 17 | + for (int i = 1; i <= V; i++) { |
| 18 | + parent[i] = i; |
| 19 | + } |
| 20 | + |
| 21 | + for (int i = 0; i < E; i++) { |
| 22 | + st = new StringTokenizer(br.readLine()); |
| 23 | + int a = Integer.parseInt(st.nextToken()); |
| 24 | + int b = Integer.parseInt(st.nextToken()); |
| 25 | + int weight = Integer.parseInt(st.nextToken()); |
| 26 | + edgeList.add(new Edge(a, b, weight)); |
| 27 | + } |
| 28 | + |
| 29 | + edgeList.sort((e1, e2) -> Integer.compare(e1.weight, e2.weight)); |
| 30 | + |
| 31 | + int total = 0; |
| 32 | + int count = 0; |
| 33 | + |
| 34 | + for (Edge edge : edgeList) { |
| 35 | + if (find(edge.from) != find(edge.to)) { |
| 36 | + union(edge.from, edge.to); |
| 37 | + total += edge.weight; |
| 38 | + count++; |
| 39 | + if (count == V - 1) break; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + System.out.println(total); |
| 44 | + } |
| 45 | + |
| 46 | + static int find(int x) { |
| 47 | + if (parent[x] == x) return x; |
| 48 | + return parent[x] = find(parent[x]); |
| 49 | + } |
| 50 | + |
| 51 | + static void union(int a, int b) { |
| 52 | + int rootA = find(a); |
| 53 | + int rootB = find(b); |
| 54 | + if (rootA != rootB) parent[rootB] = rootA; |
| 55 | + } |
| 56 | + |
| 57 | + static class Edge { |
| 58 | + int from, to, weight; |
| 59 | + |
| 60 | + Edge(int from, int to, int weight) { |
| 61 | + this.from = from; |
| 62 | + this.to = to; |
| 63 | + this.weight = weight; |
| 64 | + } |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +``` |
0 commit comments