【代码随想录算法训练营——Day59】图论——47.参加科学大会、94.城市间货物运输I

卡码网题目链接

https://kamacoder.com/problempage.php?pid=1047

https://kamacoder.com/problempage.php?pid=1152

题解
47.参加科学大会(堆优化版)





代码竟然改写对了,本来以为没希望的.再观察了一下题解的代码写的也很好,仔细看一下.

94.城市间货物运输I

一开始改动的代码超时了,仿照题解的python代码加了退出逻辑,且要写在第一层循环里面.

代码

python 复制代码
#47.参加科学大会(堆优化版)
import heapq
class Edge:
    def __init__(self, to, val):
        self.to = to
        self.val = val
    # 定义小于操作,用于堆比较
    def __lt__(self, other):
        return self.val < other.val  # 小顶堆:值小的优先

if __name__ == "__main__":
    n, m = map(int, input().split())
    graph = [[] for _ in range(n + 1)]  # 邻接表
    for _ in range(m):
        s, e, v = map(int, input().split())
        graph[s].append(Edge(e, v))
    start = 1
    end = n
    minDist = [float('inf')] * (n + 1)
    visited = [False] * (n + 1)
    heap = []
    heapq.heappush(heap, Edge(start, 0))
    minDist[start] = 0
    while heap:
        cur = heapq.heappop(heap)
        if visited[cur.to]:
            continue
        visited[cur.to] = True
        for edge in graph[cur.to]:
            if visited[edge.to] == False and minDist[cur.to] + edge.val < minDist[edge.to]:
                minDist[edge.to] = minDist[cur.to] + edge.val
            heapq.heappush(heap, Edge(edge.to, minDist[edge.to]))
    if minDist[end] == float('inf'):
        print(-1)
    else:
        print(minDist[end])
    


python 复制代码
#94.城市间货物运输I
n, m = map(int, input().split())
graph = []
for _ in range(m):
    graph.append(list(map(int, input().split())))
start = 1
end = n
minDist = [float('inf')] * (n + 1)
minDist[start] = 0
for i in range(1, n):
    updated = False
    for j in range(len(graph)):
        fromm, to, price = graph[j][0], graph[j][1], graph[j][2]
        if minDist[fromm] != float('inf') and minDist[to] > minDist[fromm] + price:
            minDist[to] = minDist[fromm] + price
            updated = True
    if not updated:  # 若边不再更新,即停止回圈
        break
if minDist[end] == float('inf'):
    print("unconnected")
else:
    print(minDist[end])
相关推荐
IronMurphy34 分钟前
【算法四十三】279. 完全平方数
算法
墨染天姬40 分钟前
【AI】Hermes的GEPA算法
人工智能·算法
papership1 小时前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_796826521 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
Beginner x_u2 小时前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
_深海凉_5 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
旖-旎6 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
谭欣辰6 小时前
C++快速幂完整实战讲解
算法·决策树·机器学习
Mr_pyx6 小时前
【LeetHOT100】随机链表的复制——Java多解法详解
算法·深度优先
AIFarmer6 小时前
【无标题】
开发语言·c++·算法