1+ '''
2+ This Prim's Algorithm Code is for finding weight of minimum spanning tree
3+ of a connected graph.
4+ For argument graph, it should be a dictionary type
5+ such as
6+ graph = {
7+ 'a': [ [3, 'b'], [8,'c'] ],
8+ 'b': [ [3, 'a'], [5, 'd'] ],
9+ 'c': [ [8, 'a'], [2, 'd'], [4, 'e'] ],
10+ 'd': [ [5, 'b'], [2, 'c'], [6, 'e'] ],
11+ 'e': [ [4, 'c'], [6, 'd'] ]
12+ }
13+
14+ where 'a','b','c','d','e' are nodes (these can be 1,2,3,4,5 as well)
15+ '''
16+
17+
118import heapq # for priority queue
219
320# prim's algo. to find weight of minimum spanning tree
4- def prims (graph ):
21+ def prims (graph_used ):
522 vis = []
623 s = [[0 ,1 ]]
724 prim = []
@@ -17,48 +34,9 @@ def prims(graph):
1734 prim .append (x )
1835 vis .append (x )
1936
20- for j in g [x ]:
37+ for j in graph_used [x ]:
2138 i = j [- 1 ]
2239 if (i not in vis ):
2340 heapq .heappush (s ,j )
2441
2542 return mincost
26-
27-
28-
29- if __name__ == "__main__" :
30-
31- # input number of nodes and edges in graph
32- n ,e = map (int ,input ().split ())
33-
34- # initializing empty graph as a dictionary (of the form {int:list})
35- g = dict (zip ([i for i in range (1 ,n + 1 )],[[] for i in range (n )]))
36-
37- # input graph data
38- for i in range (e ):
39- a ,b ,c = map (int ,input ().split ())
40- g [a ].append ([c ,b ])
41- g [b ].append ([c ,a ])
42-
43- # print weight of minimum spanning tree
44- print (prims (g ))
45-
46- ''' tests-
47- Input : 4 5
48- 1 2 7
49- 1 4 6
50- 2 4 9
51- 4 3 8
52- 2 3 6
53- Output : 19
54-
55-
56- Input : 5 6
57- 1 2 3
58- 1 3 8
59- 2 4 5
60- 3 4 2
61- 3 5 4
62- 4 5 6
63- Output : 14
64- '''
0 commit comments