Skip to content

Commit 05d0f9a

Browse files
committed
[Week04] BOJ_4386: 별자리 만들기
1 parent 875703b commit 05d0f9a

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
package study.week04;
2+
3+
import java.io.BufferedReader;
4+
import java.io.IOException;
5+
import java.io.InputStreamReader;
6+
import java.util.PriorityQueue;
7+
8+
// 별자리 만들기
9+
public class BOJ_4386 {
10+
11+
static class Point{
12+
int num;
13+
double x;
14+
double y;
15+
16+
public Point(int num, double x,double y){
17+
this.num = num;
18+
this.x = x;
19+
this.y = y;
20+
}
21+
}
22+
23+
static class Edge{
24+
int start;
25+
int end;
26+
double weight;
27+
28+
public Edge(int start, int end, double weight){
29+
this.start = start;
30+
this.end = end;
31+
this.weight = weight;
32+
}
33+
}
34+
35+
static int[] parent;
36+
static PriorityQueue<Edge> pq;
37+
38+
public static void main(String[] args) throws IOException {
39+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
40+
41+
int N = Integer.parseInt(br.readLine());
42+
Point [] points = new Point[N];
43+
44+
for(int i=0; i<N; i++){
45+
String [] s = br.readLine().split(" ");
46+
double x = Float.parseFloat(s[0]);
47+
double y = Float.parseFloat(s[1]);
48+
49+
points[i] = new Point(i, x,y);
50+
}
51+
52+
pq = new PriorityQueue<>((e1, e2) -> {
53+
if(e1.weight < e2.weight) return -1;
54+
return 1;
55+
});
56+
57+
for (int i=0; i<N; i++){
58+
for (int j = i+1; j<N; j++){
59+
double weight = distance(points[i], points[j]);
60+
pq.add(new Edge(points[i].num, points[j].num, weight));
61+
}
62+
}
63+
64+
parent = new int[N];
65+
for(int i=0; i<N; i++){
66+
parent[i] = i;
67+
}
68+
69+
double ans = 0;
70+
71+
while(!pq.isEmpty()){
72+
Edge edge = pq.poll();
73+
int start = edge.start;
74+
int end = edge.end;
75+
double cost = edge.weight;
76+
77+
if(find(start) != find(end)){
78+
ans += cost;
79+
union(start, end);
80+
}
81+
}
82+
83+
System.out.println(ans);
84+
85+
}
86+
87+
public static void union(int x, int y){
88+
int rootA = find(x);
89+
int rootB = find(y);
90+
parent[Math.min(rootA, rootB)] = Math.max(rootA, rootB);
91+
}
92+
93+
private static int find(int x) {
94+
if(x != parent[x]){
95+
parent[x] = find(parent[x]);
96+
}
97+
98+
return parent[x];
99+
}
100+
101+
private static double distance(Point p1, Point p2) {
102+
return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
103+
}
104+
}

0 commit comments

Comments
 (0)