n, m = map(int, input().split())
tot_edges, fa, ans, cnt = sorted([tuple(map(int, input().split())) for _ in range(m)], key=lambda x: x[-1]), list(range(n + 1)), 0, 0
def father(a):
if fa[a] != a: fa[a] = father(fa[a])
return fa[a]
for u, v, w in tot_edges:
if father(u) != father(v): fa[father(u)], ans, cnt = father(v), ans + w, cnt + 1
print(ans) if cnt == n - 1 else print('impossible')
上面写法不推荐,仅用于测试下python3的精简性,阅读性较高的代码如下,共15行:
n, m = map(int, input().split())
tot_edges = sorted([tuple(map(int, input().split())) for _ in range(m)], key=lambda x: x[-1])
fa = list(range(n + 1))
def father(a):
if fa[a] == a: return a
fa[a] = father(fa[a])
return fa[a]
ans, cnt = 0, 0
for u, v, w in tot_edges:
fu, fv = father(u), father(v)
if fu == fv: continue
fa[fu] = fv
ans += w
cnt += 1
print(ans) if cnt == n - 1 else print('impossible')
哈哈哈丧心病狂可还行