-
Notifications
You must be signed in to change notification settings - Fork 2
/
Main.java
81 lines (65 loc) Β· 2.1 KB
/
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package Graph.P4386;
import java.io.*;
import java.util.*;
public class Main {
static int n;
static int[] root;
static double cost;
static Node[] nodes;
static PriorityQueue<Edge> pq = new PriorityQueue<>();
public static void main(String[] args) throws Exception {
System.setIn(new FileInputStream("src/Graph/P4386/input.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
nodes = new Node[n];
for (int i = 0; i < n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
double x = Double.parseDouble(st.nextToken());
double y = Double.parseDouble(st.nextToken());
nodes[i] = new Node(x, y);
}
for (int i = 0; i < n-1; i++) {
for (int j = i+1; j < n; j++) {
Node n1 = nodes[i], n2 = nodes[j];
double cost = Math.sqrt(Math.pow(Math.abs(n1.x - n2.x), 2) + Math.pow(Math.abs(n1.y - n2.y), 2));
pq.offer(new Edge(i, j, cost));
}
}
root = new int[n];
for (int i = 0; i < n; i++) root[i] = i;
while (!pq.isEmpty()) {
Edge e = pq.poll();
if (find(e.from) == find(e.to)) continue;
merge(e.from, e.to);
cost += e.cost;
}
System.out.println(cost);
}
static int find(int n) {
if (root[n] == n) return n;
return root[n] = find(root[n]);
}
static void merge(int a, int b) {
root[find(b)] = find(a);
}
static class Node {
double x, y;
public Node(double x, double y) {
this.x = x;
this.y = y;
}
}
static class Edge implements Comparable<Edge> {
int from, to;
double cost;
public Edge(int from, int to, double cost) {
this.from = from;
this.to = to;
this.cost = cost;
}
@Override
public int compareTo(Edge o) {
return Double.compare(this.cost, o.cost);
}
}
}