forked from GreatAlgorithm-Study/AlgorithmStudy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYJ_42861.java
More file actions
72 lines (63 loc) · 1.78 KB
/
YJ_42861.java
File metadata and controls
72 lines (63 loc) · 1.78 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import java.util.Arrays;
import java.util.Comparator;
public class YJ_42861 {
static class Bridge {
int x;
int y;
int cost;
Bridge(int x, int y, int cost){
this.x = x;
this.y = y;
this.cost = cost;
}
}
public static void main(String[] args) {
int n = 4;
int[][] costs = {{0,1,1},{0,2,2},{1,2,5},{1,3,1},{2,3,8}};
System.out.println(solution(n,costs));
}
static int solution(int n, int[][] costs) {
int length = costs.length;
Bridge[] bridgeArr = new Bridge[length];
for(int i=0; i<length; i++){
if(costs[i][2] == 0){
continue;
}
bridgeArr[i] = new Bridge(costs[i][0],costs[i][1],costs[i][2]);
}
Arrays.sort(bridgeArr, Comparator.comparingInt(o -> o.cost));
int[] parent = new int[length+1];
for(int i=1; i<length+1; i++){
parent[i] = i;
}
int minCost = 0;
int line = 0;
for(Bridge bridge : bridgeArr){
if(line == n-1){ //간선수는 n-1개
break;
}
if(find(parent, bridge.x) != find(parent, bridge.y)){
union(parent,bridge.x,bridge.y);
minCost += bridge.cost;
line++;
}
}
return minCost;
}
static int find(int[] parent, int num){
if(parent[num] == num){
return parent[num];
}
return parent[num] = find(parent,parent[num]);
}
static void union(int[] parent,int num1, int num2){
if(num1 == num2){
return;
}
if(num1 > num2){
parent[num1] = num2;
}else{
parent[num2] = num1;
}
}
}