AcWing 858. prim PYTHON
原题链接
简单
作者:
Gyp
,
2020-03-21 00:02:18
,
所有人可见
,
阅读 668
n, m = map(int, input().split())
g = [[float("inf") for i in range(n+1)] for i in range(n+1)]
st = [False for i in range(n+1)]
dist = [float("inf") for i in range(n+1)]
for _ in range(m):
a, b, w = map(int, input().split())
g[a][b] = min(g[a][b], w)
g[b][a] = min(g[b][a], w)
def prim():
ans = 0
for i in range(n):
t = -1
for j in range(1,n+1):
if st[j] == False and (t == -1 or dist[j] < dist[t]):t = j
if i != 0 and dist[t] == float("inf"):return "impossible"
st[t] = True
if i != 0:ans += dist[t]
for j in range(1, n+1):dist[j] = min(dist[j], g[t][j])
return ans
print(prim())
cool
赞