最小生成树

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值