1. 程式人生 > >CCF-201412-4-最優灌溉

CCF-201412-4-最優灌溉

這題其實不難,考最小生成樹,這裡邊多過點,稠密圖。用prim演算法求最小生成樹。嗯。。。套模板。這題的n最大1000。這裡程式碼時間複雜度為O(n^2),勉強夠過這題,提交後100分,703ms。

python程式碼

def prim(graph):
    n = len(graph)
    costs = [99999 for _ in range(n)]  # 父結點到該結點的邊權值
    costs[0] = 0
    visited = [False for _ in range(n)]
    t = []
    while len(t) < n:
        # 在costs找最短邊,把該最短邊的結點加入t,標記為已訪問
        minCost = 99999
        minNode = None
        for i in range(n):
            if not visited[i] and costs[i] < minCost:
                minCost = costs[i]
                minNode = i
        t.append(minNode)
        visited[minNode] = True

        # 遍歷該結點的邊,更新最短邊
        for edge in graph[minNode]:
            if not visited[edge[0]] and edge[1] < costs[edge[0]]:
                costs[edge[0]] = edge[1]
    return costs


n, m = map(int, input().split())
# 構建帶權鄰接表
graph = [[] for _ in range(n)]
for i in range(m):
    a, b, c = map(int, input().split())
    graph[a - 1].append([b - 1, c])
    graph[b - 1].append([a - 1, c])
costs = prim(graph)
total = 0
for cost in costs:
    total += cost
print(total)