๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

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

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

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

1. ๋ฌธ์ œ ์„ค๋ช…

  • ์ž…๋ ฅ
    costs: n๊ฐœ์˜ ์„ฌ ์‚ฌ์ด์— ๋‹ค๋ฆฌ๋ฅผ ๊ฑด์„คํ•˜๋Š” ๋น„์šฉ
  • ์ถœ๋ ฅ
    ์ตœ์†Œ ๋น„์šฉ์œผ๋กœ ๋ชจ๋“  ์„ฌ์ด ์„œ๋กœ ํ†ตํ–‰ ๊ฐ€๋Šฅํ•˜๋„๋ก ๋งŒ๋“ค ๋•Œ ํ•„์š”ํ•œ ์ตœ์†Œ ๋น„์šฉ์„ return
  • ๊ทœ์น™
    1. ๋‹ค๋ฆฌ๋ฅผ ์—ฌ๋Ÿฌ ๋ฒˆ ๊ฑด๋„ˆ๋”๋ผ๋„, ๋„๋‹ฌํ•  ์ˆ˜๋งŒ ์žˆ์œผ๋ฉด ํ†ตํ–‰ ๊ฐ€๋Šฅํ•˜๋‹ค๊ณ  ๋ด…๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด A ์„ฌ๊ณผ B ์„ฌ ์‚ฌ์ด์— ๋‹ค๋ฆฌ๊ฐ€ ์žˆ๊ณ , B ์„ฌ๊ณผ C ์„ฌ ์‚ฌ์ด์— ๋‹ค๋ฆฌ๊ฐ€ ์žˆ์œผ๋ฉด A ์„ฌ๊ณผ C ์„ฌ์€ ์„œ๋กœ ํ†ตํ–‰ ๊ฐ€๋Šฅ
    2. ์„ฌ์˜ ๊ฐœ์ˆ˜ n์€ 1 ์ด์ƒ 100 ์ดํ•˜
    3. ์ž„์˜์˜ i์— ๋Œ€ํ•ด, costs[i][0] ์™€ costs[i] [1]์—๋Š” ๋‹ค๋ฆฌ๊ฐ€ ์—ฐ๊ฒฐ๋˜๋Š” ๋‘ ์„ฌ์˜ ๋ฒˆํ˜ธ๊ฐ€ ๋“ค์–ด์žˆ๊ณ , costs[i] [2]์—๋Š” ์ด ๋‘ ์„ฌ์„ ์—ฐ๊ฒฐํ•˜๋Š” ๋‹ค๋ฆฌ๋ฅผ ๊ฑด์„คํ•  ๋•Œ ๋“œ๋Š” ๋น„์šฉ
    4. ๊ฐ™์€ ์—ฐ๊ฒฐ์€ ๋‘ ๋ฒˆ ์ฃผ์–ด์ง€์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ๋˜ํ•œ ์ˆœ์„œ๊ฐ€ ๋ฐ”๋€Œ๋”๋ผ๋„ ๊ฐ™์€ ์—ฐ๊ฒฐ๋กœ ๋ด…๋‹ˆ๋‹ค. ์ฆ‰ 0๊ณผ 1 ์‚ฌ์ด๋ฅผ ์—ฐ๊ฒฐํ•˜๋Š” ๋น„์šฉ์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, 1๊ณผ 0์˜ ๋น„์šฉ์ด ์ฃผ์–ด์ง€์ง€ ์•Š์Šต๋‹ˆ๋‹ค.
    5. ๋ชจ๋“  ์„ฌ ์‚ฌ์ด์˜ ๋‹ค๋ฆฌ ๊ฑด์„ค ๋น„์šฉ์ด ์ฃผ์–ด์ง€์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์ด ๊ฒฝ์šฐ, ๋‘ ์„ฌ ์‚ฌ์ด์˜ ๊ฑด์„ค์ด ๋ถˆ๊ฐ€๋Šฅํ•œ ๊ฒƒ์œผ๋กœ ๋ด…๋‹ˆ๋‹ค.

2. ์ž…์ถœ๋ ฅ ์˜ˆ์‹œ

-

3. ์ฝ”๋“œ

def find(root, x):
    if root[x] == x:
        return x 
    root[x] = find(root, root[x]) 
    return root[x]

def union(root,x,y):
    rx, ry = find(root,x), find(root,y)  
    if rx != ry:
        root[ry] = rx

def solution(n, costs):
    answer = 0
    cnt = 0 
    root = [i for i in range(n)]
    costs = sorted(costs, key=lambda x:x[2])

    for cost in costs:
        if find(root, cost[0]) != find(root,cost[1]):
            union(root, cost[0],cost[1])
            answer+=cost[2]
            cnt += 1
        if cnt == n-1: 
            return answer

    return answer

4. ์–ด๋ ต๊ฑฐ๋‚˜ ํ—ท๊ฐˆ๋ ธ๋˜ ์ 

  1. ๊ทธ๋ฆฌ๋”” ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ์ด ๋ฌธ์ œ๋ฅผ ํ’€์–ด๊ฐ€๋Š” ๋ฐฉ๋ฒ•
  2. ๋…ธ๋“œ๋ฅผ ๋Œ์•„๊ฐ€๋ฉด์„œ ์ž‘์€ cost๋ฅผ ์„ ํƒํ•ด์•ผ๊ฒ ๋‹ค๊ณ  ์ƒ๊ฐ์€ ํ–ˆ๋Š”๋ฐ, ๋ชจ๋“  ์„ฌ์ด ํ†ตํ–‰๊ฐ€๋Šฅํ•œ ํ•œ ๊ฒƒ์„ ์–ด๋–ป๊ฒŒ ๊ฒ€์‚ฌ๋ฅผ ํ•  ์ง€ ์–ด๋ ค์› ๋‹ค.โ†’ Union & Find ์ž๋ฃŒ๊ตฌ์กฐ ํ™œ์šฉ
  3. โ†’ MST(์ตœ์†Œ ์‹ ์žฅ ํŠธ๋ฆฌ) ์ค‘ ํ•˜๋‚˜์ธ ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ด์šฉํ•ด ํ‘ธ๋Š” ๋ฌธ์ œ