๋ฐ์ํ
Notice
Recent Posts
Recent Comments
Link
์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
---|---|---|---|---|---|---|
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 |
Tags
- java
- 14942
- ์ค๋ช
- SQL
- ์นด์นด์ค
- ํ๊ธฐ
- SSAFY
- ํ๋ก๊ทธ๋๋จธ์ค
- ๋ฐฐ์ด ๋๋ฆฌ๊ธฐ 5
- 10๊ธฐ
- ๋ฑ์ฐ์ฝ์ค ์ ํ๊ธฐ
- ์ค๋ธ์
- ์ ๊ธฐ ์ฝ๋ฉ ์ธ์ฆํ๊ฐ
- PCCP
- 146355
- 142085
- ํต์ฌ
- ์ธํผ
- MySQL
- ํฐ์คํ ๋ฆฌ์ฑ๋ฆฐ์ง
- softeer
- ํด๊ฒฐ
- ์ฐ ๋ชจ์ ํ์ผ๋ง
- 165672
- ๋ฐฑ์ค
- ํผ์ฆ ์กฐ๊ฐ ์ฑ์ฐ๊ธฐ
- 59412
- ์ํํฐ์ด
- ์กฐ๊ฑด์ ๋ถํฉํ๋ ์ค๊ณ ๊ฑฐ๋ ์ํ ๊ตฌํ๊ธฐ
- ์๋ฃ
Archives
- Today
- Total
๊ฐ๋ฐ ์ฅฌ์ค
[ํ๋ก๊ทธ๋๋จธ์ค/Java] 42861 ์ฌ ์ฐ๊ฒฐํ๊ธฐ ๋ณธ๋ฌธ
๋ฐ์ํ
๐ ๋ฌธ์ ๋งํฌ: https://school.programmers.co.kr/learn/courses/30/lessons/42861
๐ ํด๊ฒฐ ๊ณผ์
ํฌ๋ฃจ์ค์นผ ์๊ณ ๋ฆฌ์ฆ์ ํ์ฉํ์ฌ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ์์ต๋๋ค. ํฌ๋ฃจ์ค์นผ ์๊ณ ๋ฆฌ์ฆ์ ๋ํ ์ค๋ช ๋ด์ฉ์ ๋ค์ ๋งํฌ์ ์์ต๋๋ค.
https://devjuice.tistory.com/41
์ด๋ฅผ ํ์ฉํจ์ผ๋ก์จ ์๊ฐ๋ณต์ก๋๋ฅผ O(ElogE) (E: costs ๋ฐฐ์ด์ ๊ธธ์ด)๋ก ์ค๊ณํ ์ ์์ต๋๋ค.
โ๏ธ ์ฝ๋
import java.util.*;
class Solution {
private int[] parent;
public int solution(int n, int[][] costs) {
int answer = 0;
parent = new int[n];
for (int i = 0; i < n; ++i) {
parent[i] = i;
}
Arrays.sort(costs, Comparator.comparingInt((int[] o) -> o[2]));
for (int[] cost : costs) {
if (findParent(cost[0]) == findParent(cost[1])) {
continue;
}
answer += cost[2];
unionParent(cost[0], cost[1]);
}
return answer;
}
public int findParent(int a) {
if (parent[a] == a) {
return parent[a] = a;
}
return parent[a] = findParent(parent[a]);
}
public void unionParent(int a, int b) {
a = findParent(a);
b = findParent(b);
if (a < b) {
parent[b] = a;
} else {
parent[a] = b;
}
}
}
๋ฐ์ํ