Machine Learning coder
def find(parent, u):
if parent[u] != u:
parent[u] = find(parent, parent[u])
return parent[u]
def unite(parent, rank, u, v):
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 solve(n, edges):
edges.sort(key=lambda x: x[2])
parent = list(range(n + 1))
rank = [0] * (n + 1)
cost = 0
edges_used = 0
for u, v, c in edges:
if find(parent, u) != find(parent, v):
unite(parent, rank, u, v)
cost += c
edges_used += 1
if edges_used == n - 1:
break
return cost
Break and Add ✅
#Google
1 · 1.8K ·