-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectingPointsOnAPlane.java
More file actions
84 lines (68 loc) · 1.84 KB
/
ConnectingPointsOnAPlane.java
File metadata and controls
84 lines (68 loc) · 1.84 KB
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
82
83
84
import java.util.*;
class ConnectingPointsOnAPlane {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int numPoints = in.nextInt();
PriorityQueue<Edge> edges = new PriorityQueue<Edge>(11, new EdgeComparator());
LinkedList<Point> disjointSets = new LinkedList<Point>();
for(int i = 1; i <= numPoints; i++){
Point newPoint = new Point(in.nextInt(), in.nextInt());
for(Point p : disjointSets)
edges.add(new Edge(newPoint, p));
disjointSets.add(newPoint);
}
System.out.printf("%.8f", Kruskal(edges, disjointSets));
System.out.println();
}
public static double Kruskal(PriorityQueue<Edge> edges, LinkedList<Point> disjointSets){
double totalLength = 0;
while(!edges.isEmpty()){
Edge curr = edges.poll();
Point firstSet = getSet(curr.first);
Point secondSet = getSet(curr.second);
if(firstSet == secondSet)
continue;
totalLength += curr.weight;
secondSet.parent = firstSet;
}
return totalLength;
}
public static Point getSet(Point p){
if(p.parent != null){
p.parent = getSet(p.parent);
return p.parent;
}
return p;
}
}
class Edge {
Point first;
Point second;
double weight;
public Edge(Point first, Point second) {
this.first = first;
this.second = second;
this.weight = Distance(first, second);
}
protected double Distance(Point first, Point second){
return Math.hypot(first.x - second.x, first.y - second.y);
}
}
class EdgeComparator implements Comparator<Edge>{
public int compare(Edge first, Edge second){
if(first.weight - second.weight > 0)
return 1;
if(first.weight - second.weight == 0)
return 0;
return -1;
}
}
class Point {
Point parent;
double x, y;
public Point(int x, int y){
parent = null;
this.x = (double)x;
this.y = (double)y;
}
}