문제
https://www.acmicpc.net/problem/1922
풀이
최소 신장 트리를 구하는 간단한 문제였다.
오늘 다른 최소 신장 트리 관련 문제(아래 링크)를 풀어서 쉽게 풀 수 있었다.
[백준] 1647 파이썬 - 도시 분할 계획
문제https://www.acmicpc.net/problem/1647풀이최소 신장 트리 문제이다.최소 신장 트리란 가장 적은 비용 + 사이클 없음 + 모든 정점이 연결되어있는 트리이다. 신장 트리에서 연결된 단 하나의 간선을 끊
jeongeunji1127.tistory.com
코드
import sys
input = sys.stdin.readline
n = int(input())
m = int(input())
graph = []
parent = list(range(n+1))
for _ in range(m):
a,b,c = map(int,input().split())
if a!=b:
graph.append((c,a,b))
graph.sort()
def find(x):
if parent[x] != x:
return find(parent[x])
return parent[x]
def union(a,b):
a = find(a)
b = find(b)
if a < b:
parent[b] = a
else:
parent[a] = b
def solution():
answer = 0
for c,a,b in graph:
if find(a) != find(b):
union(a,b)
answer += c
return answer
print(solution())
'Algorithm > Backjoon' 카테고리의 다른 글
[백준] 2668 파이썬 - 숫자고르기 (0) | 2025.01.08 |
---|---|
[백준] 1976 파이썬 - 여행 가자 (0) | 2025.01.08 |
[백준] 2138 파이썬 - 전구와 스위치 (1) | 2024.11.12 |
[백준] 1647 파이썬 - 도시 분할 계획 (0) | 2024.11.12 |
[백준] 14675 파이썬 - 단절점과 단절선 (0) | 2024.10.10 |