Preview:
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

if __name__ == "__main__":
    V = int(input("Enter the number of vertices: "))
    E = int(input("Enter the number of edges: "))
    edges = []

    print("Enter each edge as 'u v weight':")
    for _ in range(E):
        u, v, wt = map(int, input().split())
        edges.append([u, v, wt])

    result = tree(V, E, edges)
    print("The total weight of the Minimum Spanning Tree is:", result)
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