๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/programmers

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

by HandHand 2021. 3. 1.

๋ฌธ์ œ

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

ํ’€์ด ๊ณผ์ •

๋ชจ๋“  ์ •์ ์„ ์—ฐ๊ฒฐํ•˜๋Š” ์ตœ์†Œ ์‹ ์žฅ ํŠธ๋ฆฌ(MST)๋ฅผ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.

ํ”„๋ฆผ๊ณผ ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๋Š”๋ฐ ์ด๋ฒˆ์—๋Š” ํฌ๋ฃจ์Šค์นผ์„ ์‚ฌ์šฉํ–ˆ๋‹ค.

ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ ๊ฐ„์„  ์ •๋ณด๋“ค์„ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ด์ค€ ๋‹ค์Œ, ์‚ฌ์ดํด์„ ํ˜•์„ฑํ•˜์ง€ ์•Š๋Š” ๊ฐ„์„ ๋“ค์„ ํƒ์š•์ ์œผ๋กœ ์„ ํƒํ•ด์ค€๋‹ค.

์ด๋ฅผ ์œ„ํ•œ union-find ์ž๋ฃŒ๊ตฌ์กฐ๋งŒ ์‹ ๊ฒฝ์จ์„œ ๊ตฌํ˜„ํ•˜๋ฉด ๋ฌด๋‚œํžˆ ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ด๋‹ค.

์ฝ”๋“œ


def union(p, u, v):
    u, v = find(p, u), find(p, v)
    if u == v:
        return
    p[u] = v


def find(p, u):
    if p[u] == u:
        return u
    p[u] = find(p, p[u])
    return p[u]


def kruskal(v, edges):
    answer = 0
    parent = [i for i in range(v)]
    edges.sort(key=lambda x: x[2])

    for edge in edges:
        # ์ด๋ฏธ ๊ฐ™์€ ์ปดํฌ๋„ŒํŠธ๋ผ๋ฉด pass
        u, v = find(parent, edge[0]), find(parent, edge[1])
        if u == v:
            continue

        union(parent, u, v)
        answer += edge[2]
    return answer


def solution(n, costs):
    answer = kruskal(n, costs)
    return answer


n = 5
costs = [
    [0, 1, 1],
    [1, 2, 2],
    [3, 4, 3],
    [2, 3, 7],
]
print(solution(n, costs))
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€