-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathHW_42861_2.java
More file actions
58 lines (56 loc) Β· 1.67 KB
/
HW_42861_2.java
File metadata and controls
58 lines (56 loc) Β· 1.67 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
// μ¬μ ν΅ν κ°λ₯νλλ‘ μ°κ²°ν λ νμν μ΅μ λΉμ©
// μκ°λ³΅μ‘λ : n<=100, O(N logN) MST κ°λ₯
// MST : κ·Έλνμμ λͺ¨λ λ
Έλλ₯Ό μ°κ²°ν λ μ¬μ©λ μμ§λ€μ κ°μ€μΉ ν©μ μ΅μλ‘ νλ νΈλ¦¬
import java.util.*;
class HW_42861_2 {
static int[] parent;
static class Edge implements Comparable<Edge>{
int s, e, w;
public Edge(int s, int e, int w){
this.s = s;
this.e = e;
this.w = w;
}
@Override
public int compareTo(Edge o){
return Integer.compare(this.w, o.w);
}
}
public int solution(int n, int[][] costs) {
PriorityQueue<Edge> pq = new PriorityQueue<>();
// μ°μ μμνμ κ°μ μ 보 μ μ₯
for(int[] cost: costs){
pq.add(new Edge(cost[0], cost[1], cost[2]));
}
// union-find
parent = new int[n];
for(int i=0; i<n; i++){
parent[i] = i;
}
int answer = 0;
int cnt = 0; // μΆκ°λ κ°μ μ
// MST
while(!pq.isEmpty() && cnt <n-1){ // κ°μ n-1
Edge edge = pq.poll(); // μ΅μ λΉμ© κ°μ μ ν
if(find(edge.s) != find(edge.e)){
union(edge.s, edge.e);
answer += edge.w;
cnt++;
}
}
return answer;
}
private static void union(int a, int b){
a = find(a);
b = find(b);
if (a!=b){
parent[b] = a;
}
}
private static int find(int a){
if(a==parent[a]){
return a;
}
return parent[a] = find(parent[a]); // κ²½λ‘ μμΆ
}
}