Skip to content

Commit a0238cb

Browse files
authored
Merge pull request #2019 from AlgorithmWithGod/JHLEE325
[20260313] BOJ / G4 / 행성 연결 / 이준희
2 parents 89a7159 + 0572cdf commit a0238cb

1 file changed

Lines changed: 74 additions & 0 deletions

File tree

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
```java
2+
import java.io.*;
3+
import java.util.*;
4+
5+
class Edge implements Comparable<Edge> {
6+
int u, v, weight;
7+
8+
public Edge(int u, int v, int weight) {
9+
this.u = u;
10+
this.v = v;
11+
this.weight = weight;
12+
}
13+
14+
@Override
15+
public int compareTo(Edge o) {
16+
return this.weight - o.weight;
17+
}
18+
}
19+
20+
public class Main {
21+
22+
static int[] parent;
23+
24+
public static void main(String[] args) throws IOException {
25+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
26+
int N = Integer.parseInt(br.readLine());
27+
28+
List<Edge> edges = new ArrayList<>();
29+
for (int i = 0; i < N; i++) {
30+
StringTokenizer st = new StringTokenizer(br.readLine());
31+
for (int j = 0; j < N; j++) {
32+
int weight = Integer.parseInt(st.nextToken());
33+
if (i < j) {
34+
edges.add(new Edge(i, j, weight));
35+
}
36+
}
37+
}
38+
39+
Collections.sort(edges);
40+
41+
parent = new int[N];
42+
for (int i = 0; i < N; i++) parent[i] = i;
43+
44+
long cost = 0;
45+
int count = 0;
46+
47+
for (Edge edge : edges) {
48+
if (union(edge.u, edge.v)) {
49+
cost += edge.weight;
50+
count++;
51+
if (count == N - 1) break;
52+
}
53+
}
54+
55+
System.out.println(cost);
56+
}
57+
58+
static int find(int x) {
59+
if (parent[x] == x) return x;
60+
return parent[x] = find(parent[x]);
61+
}
62+
63+
static boolean union(int x, int y) {
64+
x = find(x);
65+
y = find(y);
66+
67+
if (x != y) {
68+
parent[y] = x;
69+
return true;
70+
}
71+
return false;
72+
}
73+
}
74+
```

0 commit comments

Comments
 (0)