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
| n, m = map(int, input().split())
def find_parent(parent, x): if parent[x] != x: parent[x] = find_parent(parent, parent[x])
return parent[x]
def union_parent(parent, a, b): a = find_parent(parent, a) b = find_parent(parent, b)
if a < b: parent[b] = a else: parent[a] = b
costs = [] parent = [0] * (n + 1) result = 0 last = 0
for i in range(n + 1): parent[i] = i
for i in range(m): a, b, c = map(int, input().split()) costs.append((c, a, b))
costs.sort()
for (c, a, b) in costs: if find_parent(parent, a) != find_parent(parent, b): union_parent(parent, a, b) result += c last = c
print(result - last)
|