0% found this document useful (0 votes)
6 views2 pages

DSL 7

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

DSL 7

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

ASSIGNMENT No - 07

Name- Om Santosh Songire


Roll No - 128
Batch - B3

You have a business with several offices; you want to lease phone lines to
connect them up with each other and the phone company charges different
amounts of money to connect different pairs of cities. You want a set of lines that
connects all your offices with a minimum total cost. Solve The Problem by
suggesting appropriate data structures.

Program:
class DisjointSet:
def init (self, vertices):
self.parent = {v: v for v in vertices}

def find(self, v):


if self.parent[v] != v:
self.parent[v] = self.find(self.parent[v]) # Path compression
return self.parent[v]

def union(self, u, v):


root_u =
self.find(u) root_v
= self.find(v) if
root_u != root_v:
self.parent[root_v] =
root_u return True
return False

def kruskals_algorithm(cities, edges):

ds = DisjointSet(cities)
mst = []
total_cost = 0
# Sort edges by cost
edges.sort(key=lambda x: x[2])

for u, v, cost in edges:


if ds.union(u, v):
mst.append((u, v, cost))
total_cost += cost

return mst, total_cost

# Sample input
cities = ['A', 'B', 'C', 'D']
edges = [
('A', 'B', 10),
('A', 'C', 6),
('A', 'D', 5),
('B', 'D', 15),
('C', 'D', 4)
]

mst, cost = kruskals_algorithm(cities, edges)

print("Edges in MST:")
for u, v, c in mst:
print(f"{u} - {v}: {c}")

print("Total Minimum Cost:", cost)

Output:
Edges in MST:
C - D: 4
A - D: 5
A - B: 10
Total Minimum Cost: 19

You might also like