|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class boj1197 { |
| 6 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + static StringTokenizer st; |
| 8 | + static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());} |
| 9 | + static int nextInt() {return Integer.parseInt(st.nextToken());} |
| 10 | + |
| 11 | + static ArrayList<Node> graph; |
| 12 | + static int[] parent; |
| 13 | + static int V, E, answer = 0; |
| 14 | + public static void main(String[] args) throws Exception { |
| 15 | + nextLine(); |
| 16 | + V = nextInt(); |
| 17 | + E = nextInt(); |
| 18 | + int a, b, c; |
| 19 | + graph = new ArrayList<>(); |
| 20 | + parent = new int[V+1]; |
| 21 | + for (int i = 1; i < V+1; i++) parent[i] = i; |
| 22 | + |
| 23 | + for (int i = 0; i < E; i++) { |
| 24 | + nextLine(); |
| 25 | + a = nextInt(); |
| 26 | + b = nextInt(); |
| 27 | + c = nextInt(); |
| 28 | + graph.add(new Node(a, b, c)); |
| 29 | + } |
| 30 | + |
| 31 | + graph.sort((o1, o2) -> o1.c-o2.c); |
| 32 | + |
| 33 | + int edgeCnt = 0; |
| 34 | + for (int i = 0; i < E; i++) { |
| 35 | + Node curr = graph.get(i); |
| 36 | + if (find(curr.s) == find(curr.e)) continue; |
| 37 | + answer += curr.c; |
| 38 | + union(curr.s, curr.e); |
| 39 | + edgeCnt++; |
| 40 | + if (edgeCnt == V-1) break; |
| 41 | + } |
| 42 | + System.out.println(answer); |
| 43 | + } |
| 44 | + |
| 45 | + static void union(int a, int b) { |
| 46 | + int pa = find(a); |
| 47 | + int pb = find(b); |
| 48 | + if (pa != pb) parent[pb] = pa; |
| 49 | + } |
| 50 | + |
| 51 | + static int find(int a) { |
| 52 | + if (parent[a] == a) return a; |
| 53 | + else return parent[a] = find(parent[a]); |
| 54 | + } |
| 55 | + |
| 56 | + static class Node{ |
| 57 | + int s, e, c; |
| 58 | + public Node(int s, int e, int c) { |
| 59 | + this.s = s; |
| 60 | + this.e = e; |
| 61 | + this.c = c; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +``` |
0 commit comments