import heapq
def tree(V, E, edges):
adj = [[] for _ in range(V)]
for i in range(E):
u, v, wt = edges[i]
adj[u].append((v, wt))
adj[v].append((u, wt))
pq = []
visited = [False] * V
res = 0
heapq.heappush(pq, (0, 0))
while pq:
wt, u = heapq.heappop(pq)
if visited[u]:
continue
res += wt
visited[u] = True
for v, weight in adj[u]:
if not visited[v]:
heapq.heappush(pq, (weight, v))
return res
# Take user input
V = int(input("Enter the number of vertices: "))
E = int(input("Enter the number of edges: "))
edges = []
for i in range(E):
u, v, wt = map(int, input(f"Enter edge {i + 1} (u v weight): ").split())
edges.append([u, v, wt])
# Function call and result output
print("Sum of weights of the Minimum Spanning Tree:", tree(V, E, edges))
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter