Skip to content

Commit 50410b9

Browse files
committed
Added mst : kruskal, prim #1
1 parent 09db868 commit 50410b9

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed

README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313

1414
## Graph
1515

16+
### ETC
17+
1618
### Shotest Path
1719

1820
- [Floyd-Warshall](/graph/shortest_path/floyd_warshall.py)
@@ -22,6 +24,12 @@
2224
- [Bellman-Ford](/graph/shortest_path/bellman_ford.py)
2325
- [BOJ 11657 : 타임머신](https://www.acmicpc.net/problem/11657)
2426

27+
### MST
28+
29+
- [Kruskal](/graph/mst/kruskal.py)
30+
- [Prim](/graph/mst/prim.py)
31+
- [BOJ 1197 : 최소 스패닝 트리](https://www.acmicpc.net/problem/1197)
32+
2533
## String
2634

2735
- [KMP](/string/kmp.py)

graph/mst/kruskal.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# [BOJ 1197] 최소 스패닝 트리
2+
# link : https://www.acmicpc.net/problem/1197
3+
# tag : graph, mininum spanning tree, MST, kruskal, union find
4+
# @subinium
5+
6+
import sys
7+
8+
# Kruskal Algorithm
9+
def kruskal(v, edge):
10+
edge = sorted(edge, key=lambda x: x[2])
11+
parent = [i for i in range(v+1)]
12+
result = 0
13+
14+
def find_(num):
15+
if num == parent[num] : return num
16+
parent[num] = find_(parent[num])
17+
return parent[num]
18+
19+
def union_(a, b):
20+
if a < b : parent[a] = b
21+
else : parent[b] = a
22+
23+
for st, ed, val in edge:
24+
v, w = find_(st), find_(ed)
25+
if v == w : continue
26+
union_(v, w)
27+
result += val
28+
29+
return result
30+
31+
if __name__ == '__main__':
32+
input = sys.stdin.readline
33+
V, E = map(int, input().split())
34+
edge = [tuple(map(int, input().split())) for _ in range(E)]
35+
result = kruskal(V, edge)
36+
print(result)

graph/mst/prim.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# [BOJ 1197] 최소 스패닝 트리
2+
# link : https://www.acmicpc.net/problem/1197
3+
# tag : graph, mininum spanning tree, MST, prim, priority queue
4+
# @subinium
5+
6+
import sys
7+
from heapq import heappush, heappop
8+
9+
# Prim
10+
def prim(v, edge_raw):
11+
checked = [False for _ in range(v+1)]
12+
edge = [[] for _ in range(v+1)]
13+
for st, ed, val in edge_raw:
14+
edge[st].append((val, ed))
15+
edge[ed].append((val, st))
16+
17+
pq = [(0, 1)]
18+
result = 0
19+
while pq:
20+
val, node = heappop(pq)
21+
if checked[node]: continue
22+
checked[node] = True
23+
result += val
24+
for val, ed in edge[node]:
25+
if checked[ed] : continue
26+
heappush(pq, (val, ed))
27+
28+
return result
29+
30+
# Main
31+
if __name__ == '__main__':
32+
input = sys.stdin.readline
33+
V, E = map(int, input().split())
34+
edge = [tuple(map(int, input().split())) for _ in range(E)]
35+
result = prim(V, edge)
36+
print(result)

0 commit comments

Comments
 (0)