Skip to content

Commit 66ac376

Browse files
authored
Merge pull request #293 from AlgorithmWithGod/03do-new30
[20250401] BOJ / G3 / 우주신과의 교감 / 신동윤
2 parents a9de102 + 4a545a4 commit 66ac376

File tree

1 file changed

+106
-0
lines changed

1 file changed

+106
-0
lines changed
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
import java.awt.Point;
5+
public class Main {
6+
7+
static int N, M;
8+
static Point[] points;
9+
static int[] parents;
10+
static PriorityQueue<Edge> pq;
11+
12+
static class Edge implements Comparable<Edge>{
13+
int from, to;
14+
double wt;
15+
public Edge(int from, int to, double wt) {
16+
this.from = from;
17+
this.to = to;
18+
this.wt = wt;
19+
}
20+
21+
@Override
22+
public int compareTo(Edge o) {
23+
return Double.compare(this.wt, o.wt);
24+
}
25+
}
26+
27+
public static void main(String[] args) throws IOException {
28+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
29+
StringTokenizer st = new StringTokenizer(br.readLine());
30+
N = Integer.parseInt(st.nextToken()); // 정점의 개수
31+
M = Integer.parseInt(st.nextToken()); // 이미 연결된 통로의 개수
32+
33+
points = new Point[N+1];
34+
for (int i = 1; i < N+1; i++) {
35+
st = new StringTokenizer(br.readLine());
36+
int x = Integer.parseInt(st.nextToken());
37+
int y = Integer.parseInt(st.nextToken());
38+
points[i] = new Point(x, y);
39+
}
40+
41+
makeSet();
42+
43+
for (int i = 0; i < M; i++) {
44+
// 이미 연결된 정점들에 대해 union
45+
st = new StringTokenizer(br.readLine());
46+
int a = Integer.parseInt(st.nextToken());
47+
int b = Integer.parseInt(st.nextToken());
48+
union(a, b);
49+
}
50+
51+
makePQ();
52+
double result = kruskal();
53+
System.out.printf("%.2f\n", result);
54+
br.close();
55+
}
56+
57+
static double kruskal() {
58+
double result = 0.0;
59+
while (!pq.isEmpty()) {
60+
Edge e = pq.poll();
61+
if (union(e.to, e.from)) {
62+
result += e.wt;
63+
}
64+
}
65+
return result;
66+
}
67+
68+
static void makePQ() {
69+
pq = new PriorityQueue<>();
70+
for (int i = 1; i < N; i++) {
71+
for (int j = i+1; j < N+1; j++) {
72+
pq.add(new Edge(i, j, getDist(points[i], points[j])));
73+
}
74+
}
75+
}
76+
77+
static void makeSet() {
78+
parents = new int[N+1];
79+
for (int i = 1; i < N+1; i++) {
80+
parents[i] = i;
81+
}
82+
}
83+
84+
static int find(int a) {
85+
if (parents[a] == a) return a;
86+
return parents[a] = find(parents[a]);
87+
}
88+
89+
static boolean union(int a, int b) {
90+
int aRoot = find(a);
91+
int bRoot = find(b);
92+
if (aRoot == bRoot) return false;
93+
if (aRoot < bRoot) {
94+
parents[bRoot] = aRoot;
95+
} else {
96+
parents[bRoot] = aRoot;
97+
}
98+
return true;
99+
}
100+
101+
static double getDist(Point a, Point b) {
102+
return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
103+
}
104+
}
105+
106+
```

0 commit comments

Comments
 (0)