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

BOJ 6497 - ์ „๋ ฅ๋‚œ

by HandHand 2021. 3. 8.

๋ฌธ์ œ

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

ํ’€์ด ๊ณผ์ •

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

์ฝ”๋“œ


import sys
import heapq

sys.setrecursionlimit(10**6)

parent = []


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

    parent[u] = v


def find(u):
    if parent[u] == u:
        return u

    parent[u] = find(parent[u])
    return parent[u]


def solution(N, edges):
    ret = 0

    for _ in range(N):
        cost, src, dst = heapq.heappop(edges)
        if find(src) != find(dst):
            ret += cost
            union(src, dst)

    return ret


if __name__ == '__main__':
    while 1:
        M, N = list(map(int, sys.stdin.readline().split()))
        if M == 0:
            break

        total = 0
        edges = []
        for _ in range(N):
            src, dst, cost = list(map(int, sys.stdin.readline().split()))
            edges.append([cost, src, dst])
            total += cost

        parent = [i for i in range(M)]

        heapq.heapify(edges)
        answer = total - solution(N, edges)
        print(answer)
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > boj' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ 17086 - ์•„๊ธฐ ์ƒ์–ด2  (0) 2021.03.08
BOJ 13335 - ํŠธ๋Ÿญ  (0) 2021.03.08
BOJ 6156 - Cow Contest  (0) 2021.03.08
BOJ 9625 - BABBA  (0) 2021.03.08
BOJ 11952 - ์ข€๋น„  (0) 2021.03.08

๐Ÿ’ฌ ๋Œ“๊ธ€