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

BOJ 1922 - ๋„คํŠธ์›Œํฌ ์—ฐ๊ฒฐ

by HandHand 2021. 4. 13.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 1922๋ฒˆ

ํ’€์ด ๊ณผ์ •

๋ชจ๋“  ์ปดํ“จํ„ฐ๋ฅผ ์—ฐ๊ฒฐํ•˜๋Š” ๋„คํŠธ์›Œํฌ๋ฅผ ๊ตฌ์„ฑํ•˜๋Š” ์ตœ์†Œ ๋น„์šฉ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
ํฌ๋ฃจ์Šค์นผ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ ์ด์šฉํ•ด์„œ MST ๋ฅผ ๊ตฌํ˜„ํ–ˆ์œผ๋ฉฐ union ์—ฐ์‚ฐ์—์„œ๋Š” ๋žญํฌ ์ตœ์ ํ™”์™€ ๊ฒฝ๋กœ ์••์ถ•์„ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys


def union(v1, v2):
    r1, r2 = find(v1), find(v2)
    if r1 == r2:
        return

    if rank[r1] > rank[r2]:
        parent[r2] = r1
    else:
        parent[r1] = r2
        if rank[r1] == rank[r2]:
            rank[r2] += 1


def find(v):
    if parent[v] != v:
        parent[v] = find(parent[v])

    return parent[v]


def kruskal():
    total_cost = 0

    for v in range(1, N + 1):
        parent[v] = v
        rank[v] = 0

    for frm, to, cost in sorted(edges, key=lambda edge: edge[2]):
        r1, r2 = find(frm), find(to)
        if r1 != r2:
            union(r1, r2)
            total_cost += cost

    return total_cost


def solution():
    answer = kruskal()

    return answer


if __name__ == '__main__':
    N = int(input())
    M = int(input())
    edges = [list(map(int, sys.stdin.readline().split())) for _ in range(M)]
    parent = [-1] * (N + 1)
    rank = [0] * (N + 1)

    answer = solution()
    print(answer)
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€