Baekjoon #6497

Baekjoon #6497

1개의 풀이 · Python

문제 원문 보기 ↗

SOLUTION INFO

Python · main.py

main.py
import sys

def input():
    return sys.stdin.readline().rstrip()

while True:
    n, m = map(int, input().split())
    
    if n == 0 and m == 0:
        break
    
    edge = []
    total = 0
    for _ in range(m):
        x, y, w = map(int, input().split())
        edge.append([x, y, w])
        total += w
    num_edge = 0
    edge.sort(key=lambda x: -x[2])

    # Disjoint set 구성
    dis_set = [-1 for _ in range(n+1)]
    def upward(x, change_lst):
        if dis_set[x] < 0:
            return x
        change_lst.append(x)
        return upward(dis_set[x], change_lst)

    def find_root(x):
        change_lst = []
        res = upward(x, change_lst)

        for idx in change_lst:
            dis_set[idx] = res
        return res

    def union(x, y):
        x_root = find_root(x)
        y_root = find_root(y)
        if x_root != y_root: # 두 node의 root가 다르다면?
            if dis_set[x_root] < dis_set[y_root]:
                dis_set[y_root] = x_root
            if dis_set[x_root] > dis_set[y_root]:
                dis_set[x_root] = y_root
            else:
                dis_set[x_root] = -1
                dis_set[y_root] = x_root
                
    # 크루스칼 시작
    sol = 0
    while num_edge < n-1:
        x, y, w = edge.pop()
        if find_root(x) != find_root(y):
            union(x, y)
            sol += w
            num_edge += 1

    print(total - sol)

SOLUTION DESCRIPTION

풀이 설명

등록된 풀이 설명이 없습니다.

GITHUB COMMUNITY

커뮤니티 평가

GitHub 계정으로 남긴 최신 평가 1건만 반영하며, 데이터는 매일 저장소에 동기화됩니다.

최근 동기화

체감 난이도

아직 평가 없음

첫 난이도 평가를 남겨주세요.

문제 추천

아직 평가 없음

이 문제가 도움이 되었는지 알려주세요.

이 문제 평가하기

GitHub 로그인 후 난이도를 제출하고, 원하는 경우 추천 여부도 함께 남길 수 있습니다.

추천 여부 (선택)

평가하려면 GitHub로 로그인해 주세요.

평가는 자동으로 저장소 Discussion에 기록되므로 Discussion 화면을 직접 열 필요가 없습니다. 같은 문제를 다시 평가하면 기존 평가가 갱신됩니다.

DISCUSSION

댓글

GitHub 로그인 후 작성할 수 있으며 모든 댓글은 이 저장소의 Discussions에 보관됩니다.