Trim
1.修建公路1
https://www.lanqiao.cn/problems/1124/learning/?page=1&first_category_id=1&name=%E4%BF%AE%E5%BB%BA%E5%85%AC%E8%B7%AF
import heapq
def prim(s):
hp = []
heapq.heappush(hp,(0,s))
res = 0
cnt = 0
inq = [0 for i in range(n+1)]
while hp and cnt<n:
x,u = heapq.heappop(hp)
if inq[u]:
continue
inq[u] = 1
res += x
cnt += 1
for v,w in G[u]:
heapq.heappush(hp,(w,v))
if cnt < n:
print(-1)
else:
print(res)
# 请在此输入您的代码
n,m = map(int,input().split())
G = [[] for i in range(n+1)]
for i in range(m):
u,v,w = map(int,input().split())
G[u].append((v,w))
G[v].append((u,w))
prim(1)
Kruskal
1.Trim的修建公路
def find(u):
if u==father[u]:
return u
father[u] = find(father[u])
return father[u]
def Kruskal():
cnt = 0
res = 0
for u,v,w in G:
ui,vi = find(u),find(v)
if ui==vi:
continue
father[ui] = vi
cnt += 1
res += w
if cnt == n-1:
break
if cnt < n-1:
print(-1)
else:
print(res)
# 请在此输入您的代码
n,m = map(int,input().split())
G = []
for i in range(m):
u,v,w = map(int,input().split())
G.append((u,v,w))
G.append((v,u,w))
G.sort(key=lambda x:x[2])
father = [i for i in range(n+1)]
Kruskal()