Skip to content

Commit a4afe26

Browse files
authored
[BOJ] 1197 최소 스패닝 트리 (G4)
1 parent 8e6db1c commit a4afe26

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

김지호/9주차/260301.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# https://www.acmicpc.net/problem/1197
2+
# 최소 스패닝 트리, 골드4
3+
4+
import sys
5+
import copy
6+
7+
V,E = map(int,input().split(" ")) # V(노드 개수), E(간선 개수)
8+
9+
graph = []
10+
for _ in range(E):
11+
a,b,w = map(int,input().split(" "))
12+
graph.append([a,b,w]) # a -> b : 가중치 w
13+
14+
15+
def find_parent(parents,x):
16+
while parents[x] != x:
17+
parents[x] = parents[parents[x]]
18+
x = parents[x]
19+
return x
20+
21+
22+
def union_find(parents,a,b):
23+
rootA = find_parent(parents,a)
24+
rootB = find_parent(parents,b)
25+
26+
if(rootA != rootB):
27+
parents[rootB] = rootA
28+
29+
30+
31+
# graph의 구조를 가진 그래프에서, 최소 스패닝 트리의 가중치를 구하는 함수
32+
def kruskal(V,graph):
33+
graph.sort(key=lambda x:x[2]) # 오른차순
34+
# print(f"정렬된 GRAPH : {graph}")
35+
36+
parents = [i for i in range(V+1)]
37+
38+
# print(parents)
39+
count = 0
40+
min_path = 0
41+
42+
for a,b,w in graph:
43+
# print(f"\n검사 : {a} -> {b}")
44+
if find_parent(parents,a) != find_parent(parents,b):
45+
# print(f"✅선택함")
46+
union_find(parents,a,b)
47+
count += 1
48+
min_path += w
49+
50+
51+
# 종료 조건
52+
if(count == V-1):
53+
break
54+
# else:
55+
# print(f"루프가 만들어져서 선택 X")
56+
57+
return min_path
58+
59+
answer = kruskal(V,graph)
60+
print(answer)

0 commit comments

Comments
 (0)