๊ฐœ๋ฐœ ์ฅฌ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/Java] 42861 ์„ฌ ์—ฐ๊ฒฐํ•˜๊ธฐ ๋ณธ๋ฌธ

์นดํ…Œ๊ณ ๋ฆฌ ์—†์Œ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/Java] 42861 ์„ฌ ์—ฐ๊ฒฐํ•˜๊ธฐ

DevJuice 2024. 10. 2. 19:46
๋ฐ˜์‘ํ˜•

๐Ÿ”— ๋ฌธ์ œ ๋งํฌ: https://school.programmers.co.kr/learn/courses/30/lessons/42861

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๐Ÿ”  ํ•ด๊ฒฐ ๊ณผ์ •

ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ™œ์šฉํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜์˜€์Šต๋‹ˆ๋‹ค. ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์— ๋Œ€ํ•œ ์„ค๋ช… ๋‚ด์šฉ์€ ๋‹ค์Œ ๋งํฌ์— ์žˆ์Šต๋‹ˆ๋‹ค.

https://devjuice.tistory.com/41

 

[ํ•ต์‹ฌ์ •๋ฆฌ] ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜

ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์— ๋Œ€ํ•ด์„œ ํ•ต์‹ฌ๋งŒ ๋‹ด์•„๋ณด์•˜์Šต๋‹ˆ๋‹ค.์‹œ๊ฐ„๋ณต์žก๋„: O(ElogE) (E: ๊ทธ๋ž˜ํ”„์˜ ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜) ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์•Œ๊ธฐ ์ „์— ๋จผ์ € ๋‹ค์Œ ๊ฐœ๋…์„ ์•Œ์•„์•ผ ํ•ฉ๋‹ˆ๋‹ค. ๐Ÿ” ์‹ ์žฅ ํŠธ๋ฆฌ๋ž€?ํ•˜๋‚˜์˜

devjuice.tistory.com

 

์ด๋ฅผ ํ™œ์šฉํ•จ์œผ๋กœ์จ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ 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;
        }
    }
}
๋ฐ˜์‘ํ˜•