CSP 201703-4 地铁修建 python 最小生成树,并查集

CSP 201703-4 地铁修建 python 最小生成树,并查集

题目描述

在这里插入图片描述

样例输入
6 6
1 2 4
2 3 4
3 6 7
1 4 2
4 5 5
5 6 6

样例输出
6

思路

  • 由于所有的隧道同时开始修建,则当需要花费时间最长的隧道的时间值最小时,即为修建整条地铁线路最少的时间。

  • 采用最小生成树思想,运用Kruskal算法即可求解。

  • 采用并查集思想,当第一个点和最后一个点在同一个集合时,表明此时隧道已经修建 完毕,输出最后完成的隧道所需天数即可。

代码

# http://118.190.20.162/view.page?gpid=T54
# 并查集 + Kruskal算法

n,m = map(int,input().split())

w = []
for i in range(m):
    a,b,c = map(int,input().split())
    w.append((a,b,c))

f = [i for i in range(n+1)]

def get_father(x):
    if f[x] != x:
        f[x] = get_father(f[x])
    return f[x]

def union(x,y):
    fx,fy = get_father(x),get_father(y)
    if fx != fy:
        f[fy] = fx

# 排序
w.sort(key = lambda x:x[2])

# 构建最小生成树0
for i in w:
    u,v,w = i
    if get_father(u) != get_father(v):
        union(u,v)
        if get_father(1) == get_father(n):
            print(w)
            break

猜你喜欢

转载自blog.csdn.net/weixin_45508265/article/details/125092267