-
Notifications
You must be signed in to change notification settings - Fork 0
/
kruskal.py
83 lines (55 loc) · 1.58 KB
/
kruskal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from disjointset import *
from operator import itemgetter
class graph:
def __init__(self,list,node):
self.list=list
self.node=node
self.addedge=[]
self.node_list=[]
self.sorted_edge=sorted(self.list,key=itemgetter(2))
# print(self.sorted_edge)
def kruskal(self):
ds=DisjointSets()
for i in self.node:
node=ds.makeset(i)
self.node_list.append(node)
# print("***",i.rank)
# print("^^^",self.node_list)
cost=0
for edge in self.sorted_edge:
u=self.node_list[edge[0]]
v=self.node_list[edge[1]]
w=edge[2]
# print(u,v,w)
if(ds.findset(u)!=ds.findset(v)):
self.addedge.append([u,v,w])
cost=cost+w
ds.union(u,v)
print("Nodes in kruskal along with their weights are:")
for u,v,w in self.addedge:
print(str(u),str(v),w,sep=" ")
print("Total min cost is")
print(cost)
# print(self.addedge)
def main():
G=[]
linecount=0
node=[]
file=open("input1.txt","r")
for line in file:
first=True
for edge in line.split(" "):
if first==True:
first=False
else:
v,weight=edge.split(",")
G.append((linecount,int(v),int(weight)))
node.append(linecount)
linecount+=1
# print(node)
file.close()
print(G)
g=graph(G,node)
g.kruskal()
if __name__ == '__main__':
main()