-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathJY_42861.java
More file actions
41 lines (33 loc) · 910 Bytes
/
JY_42861.java
File metadata and controls
41 lines (33 loc) · 910 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.*;
class JY_42861 {
static int[] parents;
public int solution(int n, int[][] costs) {
int answer = 0;
parents = new int[n];
for(int i=0; i<n; i++) {
parents[i] = i;
}
// 비용 순으로 정렬
Arrays.sort(costs, (o1, o2)->(o1[2]-o2[2]));
for(int[] cost: costs) {
if(find(cost[0]) != find(cost[1])) {
union(cost[0], cost[1]);
answer += cost[2];
}
}
return answer;
}
public static int find(int x) {
if(parents[x] != x) {
parents[x] = find(parents[x]);
}
return parents[x];
}
public static void union(int a, int b) {
int pa = find(a);
int pb = find(b);
if(pa != pb) {
parents[pb] = pa;
}
}
}