CCF-201412-4-最优灌溉

本文详细介绍了如何使用Prim算法解决最小生成树问题,针对稠密图的特点,通过Python代码实现并解释了算法的步骤,最后展示了在特定数据规模下(n最大1000)的时间效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这题其实不难,考最小生成树,这里边多过点,稠密图。用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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值