[Programmers] 42861번 - 섬 연결하기 [Java][C++]
[Programmers] 42861번 - 섬 연결하기 [Java][C++]
1. 아이디어
n개의 섬 사이에 다리를 건설하는 비용 costs가 주어질 때, 최소 비용으로 모든 섬이 서로 통행 가능하도록 만들 때 필요한 최소 비용을 return 하는 문제다. 최소 스패닝 트리의 대표적인 문제로 costs를 비용에 대해 오름차순 정렬한 후 크루스칼 알고리즘으로 간선을 선택하는 방식으로 해결했다.
2. 복잡도
| 시간복잡도 | 공간복잡도 |
|---|---|
| $O(E \log E)$ | $O(N)$ |
$N$ = 섬(정점) 개수(
n), $E$ = 다리 후보 개수(costs의 길이)
3. 코드
풀이 [Java][C++]
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
import java.util.*;
class Solution {
static int[] p;
static void make(int n) {
p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = i;
}
}
static int find(int x) {
if (x == p[x]) return x;
return p[x] = find(p[x]);
}
static void union(int x, int y) {
p[find(y)] = find(x);
}
public int solution(int n, int[][] costs) {
Arrays.sort(costs, (o1, o2) -> Integer.compare(o1[2], o2[2]));
make(n);
int sum = 0;
int cnt = 0;
for (int[] cost : costs) {
int x = cost[0];
int y = cost[1];
int v = cost[2];
if (find(x) == find(y)) continue;
union(x, y);
sum += v;
cnt++;
if (cnt == n - 1) break;
}
return sum;
}
}
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
#include <algorithm>
#include <vector>
using namespace std;
int p[100];
void make(int n) {
for (int i = 0; i < n; i++) {
p[i] = i;
}
}
int find(int x) {
if (x == p[x]) return x;
return p[x] = find(p[x]);
}
void unite(int x, int y) {
p[find(y)] = find(x);
}
int solution(int n, vector<vector<int>> costs) {
sort(costs.begin(), costs.end(), [](auto& o1, auto& o2) {
return o1[2] < o2[2];
});
make(n);
int sum = 0;
int cnt = 0;
for (auto& cost : costs) {
int x = cost[0];
int y = cost[1];
int v = cost[2];
if (find(x) == find(y)) continue;
unite(x, y);
sum += v;
cnt++;
if (cnt == n - 1) break;
}
return sum;
}
This post is licensed under CC BY 4.0 by the author.