AcWing 859. Kruskal算法求最小生成树 python
原题链接
简单
作者:
申侠
,
2020-10-24 15:15:25
,
所有人可见
,
阅读 386
class USD():
def __init__(self,N=10010):
self.lt = [i for i in range(N+1)]
def find(self, a):
lt = self.lt
if lt[a] !=a:
lt[a] = self.find(lt[a])
return lt[a]
def merge(self,a,b):
self.lt[self.find(a)] = self.find(b)
n,m = map(int,input().split(' '))
edges = []
for _ in range(m):
a,b,c = map(int,input().split(' '))
edges.append([c,a,b])
edges.sort()
usd = USD(n)
st = [False] * (n+1)
w = 0
cnt = 0
for c,a,b in edges:
if usd.find(a) != usd.find(b):
w += c
st[a] = st[b] = True
cnt += 1
usd.merge(a,b)
print(w) if cnt >= n-1 else print('impossible')