https://www.acmicpc.net/problem/1922
A typical MST question. Review other mst blog posts that I wrote for this kruskal implementation (that is like dijkstra but with heap)
Just one precaution is that for the last code, we should be checking if next_b is not visited, not next_a cuz we already checked that in the above visited logic.
from collections import defaultdict
import heapq
import sys
input = sys.stdin.readline
n = int(input())
m = int(input())
graph = defaultdict(list)
for _ in range(m):
a, b, c = map(int, input().split())
graph[a].append([c, a, b])
graph[b].append([c, b, a])
heap = graph[1]
heapq.heapify(heap)
ans = 0
visited = [False for _ in range(n + 1)]
visited[1] = True
while heap:
c, a, b = heapq.heappop(heap)
if not visited[b]:
visited[b] = True
ans += c
for hola in graph[b]:
next_c, next_a, next_b = hola
if not visited[next_b]:
heapq.heappush(heap, hola)
print(ans)
v+e time and nope lol
To analyze the time and space complexity of your code:
Time Complexity:
Space Complexity:
ans, visited, and loop variables is O(n) since they have a size proportional to the number of nodes.Overall, the time complexity of your code is O(mlogm) and the space complexity is O(m + n).