def min_bridge_cost(n, costs):
costs.sort(key=lambda x: x[2])
parent = [i for i in range(n)]
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
def union(a, b):
a = find(a)
b = find(b)
if a != b:
parent[b] = a
return True
return False
total = 0
for a, b, cost in costs:
if union(a, b):
total += cost
return total
n = 4
costs = [[0,1,1], [0,2,2], [1,2,5], [1,3,1], [2,3,8]]
print(min_bridge_cost(n, costs))
To embed this project on your website, copy the following code and paste it into your website's HTML: