티스토리 뷰

1. 문제

https://school.programmers.co.kr/learn/courses/30/lessons/42861

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

2. 풀이

  • 유니온 파인드를 이용해 풀이한다.
  • 각 섬 별 cost를 저장한 후, cost가 낮은 순서부터 섬을 연결하는데,
    • 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;
    }
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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
글 보관함