โ๋ฌธ์
https://www.acmicpc.net/problem/1197
Kruskal, Python3โก๏ธ๋ฉ๋ชจ๋ฆฌ: 57288 KB, ์๊ฐ: 264 ms
Prim, PyPy3โก๏ธ๋ฉ๋ชจ๋ฆฌ: 129144 KB, ์๊ฐ: 380 ms
์ต์ ์คํจ๋ ํธ๋ฆฌ, ๊ทธ๋ํ ์ด๋ก
๊ทธ๋ํ๊ฐ ์ฃผ์ด์ก์ ๋, ๊ทธ ๊ทธ๋ํ์ ์ต์ ์คํจ๋ ํธ๋ฆฌ๋ฅผ ๊ตฌํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค.
์ต์ ์คํจ๋ ํธ๋ฆฌ๋, ์ฃผ์ด์ง ๊ทธ๋ํ์ ๋ชจ๋ ์ ์ ๋ค์ ์ฐ๊ฒฐํ๋ ๋ถ๋ถ ๊ทธ๋ํ ์ค์์ ๊ทธ ๊ฐ์ค์น์ ํฉ์ด ์ต์์ธ ํธ๋ฆฌ๋ฅผ ๋งํ๋ค.
โ๐ปํ์ด
[Algorithms] ์ต์ ์ ์ฅ ํธ๋ฆฌ (Minimum Spanning Tree)
https://www.geeksforgeeks.org/what-is-minimum-spanning-tree-mst/ What is Minimum Spanning Tree (MST) - GeeksforGeeksA Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, qu
lucy-devblog.tistory.com
์ต์ ์ ์ฅ ํธ๋ฆฌ๋ ์ ๋ด์ฉ๊ณผ ๊ฐ์ด ํฌ๋ฃจ์ค์ปฌ ์๊ณ ๋ฆฌ์ฆ๊ณผ ํ๋ฆผ ์๊ณ ๋ฆฌ์ฆ์ ์ฌ์ฉํด ๊ตฌํํ ์ ์์ต๋๋ค.
ํฌ๋ฃจ์ค์ปฌ ์๊ณ ๋ฆฌ์ฆ์ Union-Find๋ฅผ ์ด์ฉํ๋ฉด ๋ฉ๋๋ค. ๊ทธ๋ฆฌ๊ณ ํ๋ฆผ ์๊ณ ๋ฆฌ์ฆ์ ์๋ ์ฌ์ดํธ๋ฅผ ์ฐธ๊ณ ํ์ต๋๋ค.
https://daegwonkim.tistory.com/191
[Python] BOJ / 1197๋ฒ / ์ต์ ์คํจ๋ ํธ๋ฆฌ
1197๋ฒ: ์ต์ ์คํจ๋ ํธ๋ฆฌ ์ฒซ์งธ ์ค์ ์ ์ ์ ๊ฐ์ V(1 ≤ V ≤ 10,000)์ ๊ฐ์ ์ ๊ฐ์ E(1 ≤ E ≤ 100,000)๊ฐ ์ฃผ์ด์ง๋ค. ๋ค์ E๊ฐ์ ์ค์๋ ๊ฐ ๊ฐ์ ์ ๋ํ ์ ๋ณด๋ฅผ ๋ํ๋ด๋ ์ธ ์ ์ A, B, C๊ฐ ์ฃผ์ด์ง๋ค. ์ด
daegwonkim.tistory.com
๐ป์ฝ๋
Kruskal's Algorithms
import sys
input = sys.stdin.readline
V, E = map(int, input().split())
edges = [list(map(int, input().split())) for _ in range(E)]
parent = [v for v in range(V+1)]
edges.sort(key= lambda x: x[2])
cost = 0
def find(x): # ํน์ ์์๊ฐ ์ด๋ ๊ทธ๋ฃน์ ์ํ๋์ง ์ฐพ๊ธฐ.
if parent[x] != x:
return find(parent[x])
return x
def union(a, b): # ๋ ๊ทธ๋ฃน์ ํ๋๋ก ํฉ์น๊ธฐ.
pA, pB = find(a), find(b)
if pA > pB:
parent[pA] = pB
else:
parent[pB] = pA
for a, b, c in edges:
if find(a) != find(b):
union(a, b)
cost += c
print(cost)
Prim's Algorithms
import sys
from heapq import heappop, heappush
input = sys.stdin.readline
INF = 1e9
n, m = map(int, input().split())
edges = [[] for _ in range(n)]
visited = [0] * n
for _ in range(m):
a, b, c = map(int, input().split())
edges[a - 1].append((c, b - 1))
edges[b - 1].append((c, a - 1))
ans = 0
q = [(0, 0)]
while q:
c, v = heappop(q)
if not visited[v]:
visited[v] = 1
ans += c
for c, u in edges[v]:
if not visited[u]:
heappush(q, (c, u))
print(ans)
๐ํ๊ธฐ
์ฒ์์๋ ํฌ๋ฃจ์ค์ปฌ ์๊ณ ๋ฆฌ์ฆ์ ์ฌ์ฉํด์ ํ์๋๋ฐ PyPy3๋ recursion limit๋ฅผ 10^6์ผ๋ก ์ค์ ํ๋ฉด ๋ฉ๋ชจ๋ฆฌ๋ฅผ ์ด๊ณผํ์ฌ Python3๋ก๋ง ๊ฐ๋ฅํ๋ค. ๊ทธ๋ฌ๋ ์ผ์ฑ์ PyPy3๋ก ์ฌ์ฉํ๊ธฐ ๋๋ฌธ์ ํ๋ฆผ ์๊ณ ๋ฆฌ์ฆ์ผ๋ก ๋ค์ ํด๋ณด์๋๋ ํ๋ฆผ์ PyPy3์์ ๊ฐ๋ฅํ๋ค.
'Coding Test > Algorithms' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 1976. ์ฌํ ๊ฐ์/Python - Gold4 (0) | 2025.08.18 |
---|---|
[๋ฐฑ์ค] 1717. ์งํฉ์ ํํ/Python - Gold5 (0) | 2025.08.17 |
[๋ฐฑ์ค] 13549. ์จ๋ฐ๊ผญ์ง3/Python - Gold5 (0) | 2025.08.15 |
[๋ฐฑ์ค] 11657. ํ์๋จธ์ /Python - Gold4 (1) | 2025.08.14 |
[๋ฐฑ์ค] 1504. ํน์ ํ ์ต๋จ ๊ฒฝ๋ก/Python - Gold4 (0) | 2025.08.12 |