|
| 1 | +package 최소스패닝트리; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStreamReader; |
| 6 | +import java.util.Comparator; |
| 7 | +import java.util.PriorityQueue; |
| 8 | +import java.util.StringTokenizer; |
| 9 | + |
| 10 | +public class BOJ_1197 { |
| 11 | + static class Edge implements Comparable<Edge> { |
| 12 | + int start; |
| 13 | + int end; |
| 14 | + int weight; |
| 15 | + |
| 16 | + public Edge(int start, int end, int weight){ |
| 17 | + this.start = start; |
| 18 | + this.end = end; |
| 19 | + this.weight = weight; |
| 20 | + } |
| 21 | + |
| 22 | + @Override |
| 23 | + public int compareTo(Edge o) { |
| 24 | + return this.weight-o.weight; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + static int v, e; |
| 29 | + static int[] parent; |
| 30 | + static int[] rank; |
| 31 | + static PriorityQueue<Edge> edges; |
| 32 | + public static void main(String[] args) throws IOException { |
| 33 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 34 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 35 | + |
| 36 | + v = Integer.parseInt(st.nextToken()); |
| 37 | + e = Integer.parseInt(st.nextToken()); |
| 38 | + |
| 39 | + parent = new int[v+1]; |
| 40 | + rank = new int[v+1]; |
| 41 | + edges = new PriorityQueue<>(); |
| 42 | + |
| 43 | + for(int i=1; i<=v; i++){ |
| 44 | + parent[i] = i; |
| 45 | + } |
| 46 | + |
| 47 | + for(int i=0; i<e; i++){ |
| 48 | + st = new StringTokenizer(br.readLine()); |
| 49 | + int start = Integer.parseInt(st.nextToken()); |
| 50 | + int end = Integer.parseInt(st.nextToken()); |
| 51 | + int weight = Integer.parseInt(st.nextToken()); |
| 52 | + |
| 53 | + edges.add(new Edge(start, end, weight)); |
| 54 | + } |
| 55 | + |
| 56 | + int sum = 0; |
| 57 | + while(!edges.isEmpty()){ |
| 58 | + Edge edge = edges.poll(); |
| 59 | + |
| 60 | + if(find(edge.start)==find(edge.end))continue; |
| 61 | + |
| 62 | + union(edge.start, edge.end); |
| 63 | + sum += edge.weight; |
| 64 | + } |
| 65 | + |
| 66 | + System.out.println(sum); |
| 67 | + } |
| 68 | + |
| 69 | + static int find(int x){ |
| 70 | + if(parent[x]==x)return x; |
| 71 | + return parent[x]=find(parent[x]); |
| 72 | + } |
| 73 | + |
| 74 | + static void union(int x, int y){ |
| 75 | + x = find(x); |
| 76 | + y = find(y); |
| 77 | + |
| 78 | + if(x==y)return; |
| 79 | + |
| 80 | + if(rank[x]<rank[y]){ |
| 81 | + parent[x] = y; |
| 82 | + } |
| 83 | + else{ |
| 84 | + parent[y] = x; |
| 85 | + |
| 86 | + if(rank[x]==rank[y]){ |
| 87 | + rank[x]++; |
| 88 | + } |
| 89 | + } |
| 90 | + } |
| 91 | +} |
0 commit comments