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

거북이·2023년 8월 26일
0

백준[골드4]

목록 보기
44/59
post-thumbnail

💡문제접근

  • 마을을 두 개로 분할하고 나머지 길의 유지비의 합을 최소로 하려면 선택된 간선들을 오름차순으로 정렬하고 간선의 가중치가 가장 높은 값을 제거해야한다.

💡코드(메모리 : 230516KB, 시간 : 5324ms)

import sys
input = sys.stdin.readline

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().strip().split())
parent = [0] * (N+1)
edges = []
selected = []

for i in range(1, N+1):
    parent[i] = i

for _ in range(M):
    A, B, C = map(int, input().strip().split())
    edges.append([C, A, B])
edges.sort()

for edge in edges:
    cost, a, b = edge
    if find_parent(parent, a) != find_parent(parent, b):
        union_parent(parent, a, b)
        selected.append(cost)

selected.sort()
selected.pop()
print(sum(selected))

💡소요시간 : 34m

0개의 댓글