Skip to content

Commit a358194

Browse files
authored
[20250912] BOJ / P5 / 행성 터널 / 이강현
1 parent 2dea92d commit a358194

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
public class Main {
6+
static class Vertex{
7+
int num;
8+
long value;
9+
10+
public Vertex(int num, long value) {
11+
this.num = num;
12+
this.value = value;
13+
}
14+
}
15+
16+
static class Edge{
17+
int from,to;
18+
long value;
19+
20+
public Edge(int from, int to, long value) {
21+
this.from = from;
22+
this.to = to;
23+
this.value = value;
24+
}
25+
}
26+
27+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
28+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
29+
static StringTokenizer st;
30+
static int N;
31+
static List<long[]> xyz = new ArrayList<>();
32+
static int[] root;
33+
static PriorityQueue<Edge> pq = new PriorityQueue<>((a,b) -> Long.compare(a.value, b.value));
34+
35+
public static void main(String[] args) throws IOException {
36+
N = Integer.parseInt(br.readLine());
37+
root = new int[N];
38+
for (int i = 0; i < N; i++) {
39+
root[i] = i;
40+
}
41+
42+
for (int i = 0; i < N; i++) {
43+
st = new StringTokenizer(br.readLine());
44+
long x = Long.parseLong(st.nextToken());
45+
long y = Long.parseLong(st.nextToken());
46+
long z = Long.parseLong(st.nextToken());
47+
xyz.add(new long[]{i, x, y, z});
48+
}
49+
50+
for (int i = 1; i <= 3; i++) {
51+
int cur = i;
52+
Collections.sort(xyz, (a, b) -> Long.compare(a[cur], b[cur]));
53+
54+
for (int j = 0; j < N-1; j++) {
55+
long[] p1 = xyz.get(j);
56+
long[] p2 = xyz.get(j+1);
57+
long cost = Math.abs(p2[cur] - p1[cur]);
58+
pq.offer(new Edge((int)p1[0], (int)p2[0], cost));
59+
}
60+
}
61+
62+
int cnt = 0;
63+
long ans = 0;
64+
while(!pq.isEmpty()) {
65+
Edge cur = pq.poll();
66+
if(cnt == N-1) break;
67+
if(union(cur.from, cur.to)){
68+
ans += cur.value;
69+
cnt++;
70+
}
71+
}
72+
bw.write(ans+"");
73+
bw.close();
74+
}
75+
76+
public static int find(int cur){
77+
if(root[cur] == cur) return cur;
78+
else return root[cur] = find(root[cur]);
79+
}
80+
81+
public static boolean union(int a, int b){
82+
int rootA = find(a);
83+
int rootB = find(b);
84+
85+
if(rootA == rootB){
86+
return false;
87+
}else if(rootA < rootB){
88+
root[rootA] = rootB;
89+
}else{
90+
root[rootB] = rootA;
91+
}
92+
return true;
93+
}
94+
}
95+
```

0 commit comments

Comments
 (0)