Skip to content

Commit fdfaf68

Browse files
committed
BOJ_16398 : 행성 연결
1 parent 3b1767f commit fdfaf68

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Diff for: week8/BOJ_16398(행성 연결).java

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import java.io.*;
2+
import java.util.*;
3+
4+
public class Main {
5+
6+
public static int[] parent;
7+
8+
public static void main(String[] args) throws IOException {
9+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
10+
int N = Integer.parseInt(br.readLine());
11+
parent = new int[N];
12+
PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> Integer.compare(o1[2], o2[2]));
13+
for(int i=0; i<N; i++) {
14+
parent[i] = i;
15+
StringTokenizer st = new StringTokenizer(br.readLine());
16+
for(int j=0; j<N; j++) {
17+
int cost = Integer.parseInt(st.nextToken());
18+
if(i < j) {
19+
pq.add(new int[]{i, j, cost});
20+
}
21+
}
22+
}
23+
24+
long minCost = 0;
25+
while(!pq.isEmpty()) {
26+
int[] edge = pq.poll();
27+
int v1 = edge[0];
28+
int v2 = edge[1];
29+
int cost = edge[2];
30+
31+
if(union(v1, v2)) {
32+
minCost += cost;
33+
}
34+
}
35+
System.out.println(minCost);
36+
}
37+
38+
public static int find(int x) {
39+
if(parent[x] == x) {
40+
return x;
41+
}
42+
parent[x] = find(parent[x]);
43+
return parent[x];
44+
}
45+
46+
public static boolean union(int x, int y) {
47+
x = find(x);
48+
y = find(y);
49+
if(x == y) {
50+
return false;
51+
}
52+
parent[y] = x;
53+
return true;
54+
}
55+
}

0 commit comments

Comments
 (0)