AcWing 858. Prim算法求最小生成树 python
原题链接
简单
作者:
申侠
,
2020-10-23 20:11:56
,
所有人可见
,
阅读 371
INF = float('inf')
class Graph(object):
def __init__(self, n=505):
self.matrix = [[INF for _ in range(n)]for _ in range(n)]
self.n = n
def add(self,a,b,w):
self.matrix[a][b] = min(self.matrix[a][b],w)
def prim(self,n):
cnt = 0
p = [INF] * (n+1)
st = [False] * (n+1)
for _ in range(n):
l = -1
for idx, i in enumerate(p[1:]):
if not st[idx+1] and (l == -1 or p[l] > p[idx+1]):
l = idx+1
st[l] = True
if l != 1 and p[l] == INF:
return 'impossible'
if l != 1:
cnt += p[l]
for i in range(1,n+1):
if not st[i]:
p[i] = min(p[i], self.matrix[l][i])
return cnt
n,m = map(int, input().split(' '))
g = Graph()
for _ in range(m):
a,b,w = map(int,input().split(' '))
g.add(a,b,w)
g.add(b,a,w)
print(g.prim(n))