|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + static class node { |
| 8 | + double x, y; |
| 9 | + |
| 10 | + public node(double x, double y) { |
| 11 | + this.x = x; |
| 12 | + this.y = y; |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + static class edge implements Comparable<edge> { |
| 17 | + int from, to; |
| 18 | + double weight; |
| 19 | + |
| 20 | + public edge(int from, int to, double weight) { |
| 21 | + this.from = from; |
| 22 | + this.to = to; |
| 23 | + this.weight = weight; |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public int compareTo(edge o) { |
| 28 | + return Double.compare(this.weight, o.weight); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + static int[] parent; |
| 33 | + |
| 34 | + public static void main(String[] args) throws IOException { |
| 35 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 36 | + StringTokenizer st; |
| 37 | + |
| 38 | + int n = Integer.parseInt(br.readLine()); |
| 39 | + node[] stars = new node[n]; |
| 40 | + |
| 41 | + for (int i = 0; i < n; i++) { |
| 42 | + st = new StringTokenizer(br.readLine()); |
| 43 | + double x = Double.parseDouble(st.nextToken()); |
| 44 | + double y = Double.parseDouble(st.nextToken()); |
| 45 | + stars[i] = new node(x, y); |
| 46 | + } |
| 47 | + |
| 48 | + List<edge> edges = new ArrayList<>(); |
| 49 | + for (int i = 0; i < n; i++) { |
| 50 | + for (int j = i + 1; j < n; j++) { |
| 51 | + double dist = Math.sqrt(Math.pow(stars[i].x - stars[j].x, 2) + Math.pow(stars[i].y - stars[j].y, 2)); |
| 52 | + edges.add(new edge(i, j, dist)); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + Collections.sort(edges); |
| 57 | + |
| 58 | + parent = new int[n]; |
| 59 | + for (int i = 0; i < n; i++) parent[i] = i; |
| 60 | + |
| 61 | + double result = 0; |
| 62 | + int cnt = 0; |
| 63 | + for (edge e : edges) { |
| 64 | + if (union(e.from, e.to)) { |
| 65 | + result += e.weight; |
| 66 | + cnt++; |
| 67 | + if (cnt == n - 1) break; |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + System.out.printf("%.2f\n", result); |
| 72 | + } |
| 73 | + |
| 74 | + static int find(int x) { |
| 75 | + if (parent[x] == x) return x; |
| 76 | + return parent[x] = find(parent[x]); |
| 77 | + } |
| 78 | + |
| 79 | + static boolean union(int a, int b) { |
| 80 | + a = find(a); |
| 81 | + b = find(b); |
| 82 | + if (a == b) return false; |
| 83 | + parent[b] = a; |
| 84 | + return true; |
| 85 | + } |
| 86 | +} |
| 87 | +``` |
0 commit comments