|
| 1 | +package BOJ.boj1774; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + static int[] parent; |
| 7 | + |
| 8 | + static class Node { |
| 9 | + int x, y; |
| 10 | + double w; |
| 11 | + |
| 12 | + public Node(int x, int y, double w) { |
| 13 | + this.x = x; |
| 14 | + this.y = y; |
| 15 | + this.w = w; |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + public static void main(String[] args) { |
| 20 | + Scanner sc = new Scanner(System.in); |
| 21 | + |
| 22 | + int n = sc.nextInt(); // 우주신의 개수 |
| 23 | + int m = sc.nextInt(); // 연결된 통로의 개수 |
| 24 | + |
| 25 | + parent = new int[n + 1]; |
| 26 | + for (int i = 1; i <= n; i++) { |
| 27 | + parent[i] = i; |
| 28 | + } |
| 29 | + |
| 30 | + int[][] gods = new int[n + 1][2]; // 우주신들 좌표 |
| 31 | + for (int i = 1; i <= n; i++) { |
| 32 | + gods[i][0] = sc.nextInt(); |
| 33 | + gods[i][1] = sc.nextInt(); |
| 34 | + } |
| 35 | + |
| 36 | + for (int i = 0; i < m; i++) { |
| 37 | + int x = sc.nextInt(); |
| 38 | + int y = sc.nextInt(); |
| 39 | + |
| 40 | + union(x, y); |
| 41 | + } |
| 42 | + |
| 43 | + PriorityQueue<Node> pq = new PriorityQueue<>((o1, o2) -> Double.compare(o1.w, o2.w)); |
| 44 | + |
| 45 | + for (int i = 1; i <= n; i++) { |
| 46 | + for (int j = i + 1; j <= n; j++) { |
| 47 | + int x1 = gods[i][0]; |
| 48 | + int y1 = gods[i][1]; |
| 49 | + int x2 = gods[j][0]; |
| 50 | + int y2 = gods[j][1]; |
| 51 | + |
| 52 | + double dist = Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); |
| 53 | + |
| 54 | + pq.offer(new Node(i, j, dist)); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + double result = 0; |
| 59 | + |
| 60 | + while (!pq.isEmpty()) { |
| 61 | + Node cur = pq.poll(); |
| 62 | + |
| 63 | + if (union(cur.x, cur.y)) { |
| 64 | + result += cur.w; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + System.out.print(String.format("%.2f", result)); |
| 69 | + } |
| 70 | + |
| 71 | + public static int find(int x) { |
| 72 | + if (parent[x] == x) { |
| 73 | + return x; |
| 74 | + } |
| 75 | + return parent[x] = find(parent[x]); |
| 76 | + } |
| 77 | + public static boolean union(int x, int y) { |
| 78 | + int a = find(x); |
| 79 | + int b = find(y); |
| 80 | + |
| 81 | + if (a != b) { |
| 82 | + parent[a] = y; |
| 83 | + return true; |
| 84 | + } |
| 85 | + |
| 86 | + return false; |
| 87 | + } |
| 88 | +} |
0 commit comments