티스토리 뷰
1. 문제
https://school.programmers.co.kr/learn/courses/30/lessons/42861
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
2. 풀이
- 유니온 파인드를 이용해 풀이한다.
- 각 섬 별 cost를 저장한 후, cost가 낮은 순서부터 섬을 연결하는데,
- union-find를 이용해서
- 이미 연결된 경우(사이클이 있는 경우) 섬을 연결하지 않고
- 연결되지 않은 경우(사이클이 없는 경우) 섬을 연결한다.
- union-find를 이용해서
3. 코드
import java.util.*;
class Node {
int from, to, cost;
public Node(int from, int to, int cost){
this.from = from;
this.to = to;
this.cost = cost;
}
}
class Solution {
private int find(int[] parents, int n){
if(parents[n] == n) return n;
return parents[n] = find(parents, parents[n]);
}
private void union(int[] parents, int a, int b){
int rootA = find(parents, a);
int rootB = find(parents, b);
if(rootA != rootB){
parents[rootB] = rootA;
}
}
public int solution(int n, int[][] costs) {
int answer = 0;
ArrayList<Node> list = new ArrayList<>();
int[] parents = new int[n];
for(int i = 0; i < n; i++){
parents[i] = i;
}
for(int i = 0; i < costs.length; i++){
list.add(new Node(costs[i][0], costs[i][1], costs[i][2]));
}
Collections.sort(list, new Comparator<Node>(){
@Override
public int compare(Node n1, Node n2){
return Integer.compare(n1.cost, n2.cost);
}
});
for(Node node : list){
if(find(parents, node.from) != find(parents, node.to)){ // 사이클이 형성되지 않으면
union(parents, node.from, node.to);
answer += node.cost;
}
}
return answer;
}
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[JAVA/플로이드 와샬] 프로그래머스 합승 택시 요금 (0) | 2022.10.26 |
---|---|
[JAVA/DP] 프로그래머스 스티커 모으기(2) (0) | 2022.10.25 |
[JAVA/이분탐색] 프로그래머스 징검다리 건너기 (0) | 2022.10.18 |
[MySQL/DATEDIFF] 프로그래머스 조건별로 분류하여 주문상태 출력하기 (0) | 2022.10.16 |
[JAVA/구현] 프로그래머스 행렬 테두리 회전하기 (0) | 2022.08.19 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- BFS
- 11503
- 2981
- hc-06
- 라즈베리파이
- 백준
- FTP
- 블루투스
- 자바
- c++
- hackerrank
- 프로그래머스
- git
- DP
- ESP8266
- 스티커모으기2
- mysql
- 구슬 탈출2
- the pads
- 라즈비안
- java
- 합승 택시 요금
- 메일서버
- dht11
- 집배원 한상덕
- 키 순서
- 워드프레스
- 아두이노
- dovecot
- 리눅스
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함