IT/알고리즘

[백준 Python] 1647번 도시 분할 계획

와잉 2025. 1. 18. 10:54

백준 파이썬 1647번 도시 분할 계획

Gold 4

 

https://www.acmicpc.net/problem/1647

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
def find_parent(parent, x):
    if parent[x] != x:
        parent[x] = find_parent(parent, parent[x])
    return parent[x]
def union_parent(parent, a, b):
    a = find_parent(parent, a)
    b = find_parent(parent, b)
    if a < b:
        parent[b] = a
    else:
        parent[a] = b
        
n, m = map(int, input().split())
parent = [0]*(n+1)
edges = []
result = 0
for i in range(1, n+1):
    parent[i] = i
for _ in range(m):
    a, b, cost = map(int, input().split())
    edges.append((cost, a, b))
edges.sort()
last = 0
for edge in edges:
    cost, a, b = edge
    if find_parent(parent, a) != find_parent(parent, b):
        union_parent(parent, a,  b)
        result += cost
        last=cost
print(result-last)

 

문제를 읽어보면 최소 스패닝 트리에 관한 문제라는 것을 알 수 있다.

유지비의 합을 최소화하면서 두 마을로 나누기 위해서는 마지막 경로로 이어지는 마을만 따로 분리하면 된다.

for edge in edges:
    cost, a, b = edge
    if find_parent(parent, a) != find_parent(parent, b):
        union_parent(parent, a,  b)
        result += cost
        last=cost
print(result-last)

 

반응형