1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| def init_parent(parent, n): for i in range(n): parent[i] = i
def find(parent, x): if parent[x] != x: parent[x] = find(parent, parent[x]) return parent[x]
return x
def union(parent, a, b): a = find(parent, a) b = find(parent, b)
if a < b: parent[b] = a else: parent[a] = b
v, e = map(int, input().split()) edges = [] parent = [0] * (v + 1) result = 0
for i in range(e): a, b, cost = map(int, input().split()) edges.append((cost, a, b))
edges.sort()
init_parent(parent, v + 1)
for (cost, a, b) in edges: if find(parent, a) != find(parent, b): union(parent, a, b) result += cost
print(result)
|