1
+ """
2
+ 6 8
3
+ 1 2 7
4
+ 1 3 5
5
+ 2 3 2
6
+ 2 4 6
7
+ 2 5 9
8
+ 3 6 1
9
+ 4 5 11
10
+ 5 6 12
11
+ """
12
+ import sys
13
+ input = sys .stdin .readline
14
+
15
+ def find_parent (parent , x ):
16
+ """ 부모 노드를 찾기 위해 재귀 수행"""
17
+ if parent [x ] != x :
18
+ parent [x ] = find_parent (parent , parent [x ])
19
+ return parent [x ]
20
+
21
+ def union_parent (parent , a , b ):
22
+ """ 부모 노드 비교(사이클 판별)후 부모 노드 업데이트 """
23
+ a = find_parent (parent , a )
24
+ b = find_parent (parent , b )
25
+ if a < b :
26
+ parent [b ] = a
27
+ else :
28
+ parent [a ] = b
29
+
30
+ if __name__ == "__main__" :
31
+ V , E = map (int , input ().split ()) # make graph
32
+ graph = []
33
+ for _ in range (E ):
34
+ a , b , cost = map (int , input ().split ())
35
+ graph .append ([a , b , cost ])
36
+ graph .sort (key = lambda x :x [2 ])
37
+
38
+
39
+ parent = [0 ] * (V + 1 ) # make parent table
40
+ for i in range (1 , V + 1 ):
41
+ parent [i ] = i
42
+
43
+ costs , mst = 0 , [] # get mst
44
+ for i in range (E ):
45
+ a , b , cost = graph [i ]
46
+ if find_parent (parent , a ) != find_parent (parent , b ):
47
+ union_parent (parent , a , b )
48
+ mst .append ((a , b ))
49
+ costs += cost
50
+
51
+ print (mst )
52
+ print (costs )
0 commit comments