Here is the problem statement for Problem 3
The buildings and connections can be represented as a graph. To minimize costs while connecting all buildings:
(3, 4, 1)
→ Total cost = 1(2, 3, 2)
→ Total cost = 3(1, 3, 3)
→ Total cost = 6This is a classical Minimum Spanning Tree (MST) problem. The goal is to find a subset of edges that:
We use Kruskal’s Algorithm, which efficiently builds the MST by:
If after processing all edges, not all nodes are connected, output -1
.
The Union-Find data structure, also known as Disjoint Set Union (DSU), is a powerful tool for solving connectivity problems. It efficiently keeps track of elements that are partitioned into disjoint (non-overlapping) sets and supports two key operations:
def find(parent, node):
# Path compression for efficiency
if parent[node] != node:
parent[node] = find(parent, parent[node])
return parent[node]
def union(parent, rank, u, v):
# Union by rank
root_u = find(parent, u)
root_v = find(parent, v)
if root_u != root_v:
if rank[root_u] > rank[root_v]:
parent[root_v] = root_u
elif rank[root_u] < rank[root_v]:
parent[root_u] = root_v
else:
parent[root_v] = root_u
rank[root_u] += 1
def minimum_spanning_tree(n, edges):
# Initialize Union-Find data structure
parent = [i for i in range(n + 1)]
rank = [0] * (n + 1)
# Sort edges by weight
edges.sort(key=lambda x: x[2])
total_cost = 0
edge_count = 0
for u, v, w in edges:
if find(parent, u) != find(parent, v):
union(parent, rank, u, v)
total_cost += w
edge_count += 1
# Stop early if we have connected all nodes
if edge_count == n - 1:
break
# Check if all nodes are connected
root_set = set(find(parent, i) for i in range(1, n + 1))
if len(root_set) > 1:
return -1
return total_cost
# Input reading
n, m = map(int, input().split())
edges = []
for _ in range(m):
u, v, w = map(int, input().split())
edges.append((u, v, w))
# Output the result
result = minimum_spanning_tree(n, edges)
print(result)
Kudos to all the participants who attempted this problem. Keep coding and learning!
(Special mention to PeithonKing for solving it in Rust!)