DSL 7
DSL 7
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}
ds = DisjointSet(cities)
mst = []
total_cost = 0
# Sort edges by cost
edges.sort(key=lambda x: x[2])
# Sample input
cities = ['A', 'B', 'C', 'D']
edges = [
('A', 'B', 10),
('A', 'C', 6),
('A', 'D', 5),
('B', 'D', 15),
('C', 'D', 4)
]
print("Edges in MST:")
for u, v, c in mst:
print(f"{u} - {v}: {c}")
Output:
Edges in MST:
C - D: 4
A - D: 5
A - B: 10
Total Minimum Cost: 19