Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 92855e8

Browse files
이지영: [PG] 42861 섬 연결하기_241018
1 parent a4bb43b commit 92855e8

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

‎Programmers/Level3/JY_42861.java‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import java.util.*;
2+
3+
class Solution {
4+
5+
static int[] parents;
6+
7+
public int solution(int n, int[][] costs) {
8+
int answer = 0;
9+
10+
parents = new int[n];
11+
for(int i=0; i<n; i++) {
12+
parents[i] = i;
13+
}
14+
15+
// 비용 순으로 정렬
16+
Arrays.sort(costs, (o1, o2)->(o1[2]-o2[2]));
17+
18+
for(int[] cost: costs) {
19+
if(find(cost[0]) != find(cost[1])) {
20+
union(cost[0], cost[1]);
21+
answer += cost[2];
22+
}
23+
}
24+
25+
return answer;
26+
}
27+
public static int find(int x) {
28+
if(parents[x] != x) {
29+
parents[x] = find(parents[x]);
30+
}
31+
return parents[x];
32+
}
33+
public static void union(int a, int b) {
34+
int pa = find(a);
35+
int pb = find(b);
36+
37+
if(pa != pb) {
38+
parents[pb] = pa;
39+
}
40+
}
41+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /