HW5_박권수_2015104173.py
1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import numpy as np
#Kruskal Algorithm
parent = dict()
rank = dict()
def make_singleton_set(v) :
parent[v] = v
rank[v] = 1
def find(v) :
if(parent[v] != v) :
parent[v] = find(parent[v])
return parent[v]
def union(r1, r2) :
if(r1 != r2) :
if(rank[r1] > rank[r2]) :
parent[r2] = r1
rank[r1] += rank[r2]
else :
parent[r1] = r2
if(rank[r1] == rank[r2]) :
rank[r2] += rank[r1]
def Kruskal(graph) :
#n = 정점의 수 / m = 엣지의 수
n = len(graph['vertices'])
m = len(graph['edges'])
#엣지를 전부 찾은 후 비내림차순으로 정렬한다.
edge_list = list(graph['edges'])
edge_list.sort()
#초기화한다
for v in graph['vertices'] :
make_singleton_set(v)
F = set()
index = 0
while len(F) < n - 1 :
e = edge_list[index]
p = find(e[1])
q = find(e[2])
if(p == q) :
union(p, q)
F.add(e)
index += 1
return F
graph = {
'vertices': ['A', 'B', 'C', 'D', 'E'],
'edges': set([
(1, 'A', 'B'),
(3, 'A', 'C'),
(3, 'B', 'C'),
(6, 'B', 'D'),
(4, 'C', 'D'),
(2, 'C', 'E'),
(5, 'D', 'E'),
])
}
mst = Kruskal(graph)
print(mst)