数据中心(优化MST)

版权声明:本文为博主原创文章,点个赞随便转 https://blog.csdn.net/qq_20200047/article/details/88360117
时间限制: 1.0s
内存限制: 512.0MB
问题描述:


样例输入

4
5
1
1 2 3
1 3 4
1 4 5
2 3 8
3 4 2

样例输出

4

样例说明

  下图是样例说明。

求最小生成树的最大边,注意要用优化算法。

 
class node:
    fro=to=dist=0
def getfx(x):
    if fa[x]==x:
        return fa[x]
    fa[x] = getfx(fa[x])
    return fa[x]
def merge(x,y):
    tx = getfx(x)
    ty = getfx(y)
    fa[tx] = ty    
while True:
    try:
        graph = []
        n = int(input())
        m = int(input())
        root = int(input())
        for i in range(m):
            a,b,c = map(int,input().split())
            graph.append([a,b,c])
            #print(graph[i].dist)
        graph = sorted(graph,key = lambda x:x[2])
        # for i in range(m):
            # print(graph[i][2])
        fa = [0 for i in range(1005)]
        for i in range(n+1):
            fa[i]=i
        #print(1)
        # for i in range(m):
            # print(graph[i].dist)
        ans = 0
        last = n
        k = 0
        while k<m and last>1:
            u = graph[k][0]
            v = graph[k][1]
            if not (getfx(u)==getfx(v)):
                merge(u,v)
                last-=1
                #ans+=graph[k][2]
                ans = max(ans,graph[k][2])
            k+=1                
        print(ans)    
    except:             
        break
 
 

猜你喜欢

转载自blog.csdn.net/qq_20200047/article/details/88360117