当前位置: 首页 > news >正文

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

卡码网题目链接
https://kamacoder.com/problempage.php?pid=1047
https://kamacoder.com/problempage.php?pid=1152

题解
47.参加科学大会(堆优化版)
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
代码竟然改写对了,本来以为没希望的.再观察了一下题解的代码写的也很好,仔细看一下.

94.城市间货物运输I
一开始改动的代码超时了,仿照题解的python代码加了退出逻辑,且要写在第一层循环里面.

代码

#47.参加科学大会(堆优化版)
import heapq
class Edge:def __init__(self, to, val):self.to = toself.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 = 1end = nminDist = [float('inf')] * (n + 1)visited = [False] * (n + 1)heap = []heapq.heappush(heap, Edge(start, 0))minDist[start] = 0while heap:cur = heapq.heappop(heap)if visited[cur.to]:continuevisited[cur.to] = Truefor 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.valheapq.heappush(heap, Edge(edge.to, minDist[edge.to]))if minDist[end] == float('inf'):print(-1)else:print(minDist[end])

在这里插入图片描述
在这里插入图片描述

#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 = Falsefor 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] + priceupdated = Trueif not updated:  # 若边不再更新,即停止回圈break
if minDist[end] == float('inf'):print("unconnected")
else:print(minDist[end])
http://www.dtcms.com/a/573010.html

相关文章:

  • 做网站推广前途某互联网公司开发官网的首页
  • 网站未收录wordpress设置假阅读量
  • 将大规模shp白模贴图转3dtiles倾斜摄影,并可单体化拾取建筑
  • CMP7(类Cloudera CMP 7 404版华为Kunpeng)用开源软件Label Studio做数据标注
  • Go、DevOps运维开发实战(视频教程)
  • 25.Spring Boot 启动流程深度解析:从run()到自动配置
  • Spring Boot 实现多语言国际化拦截器
  • 神经网络—— 人工神经网络导论
  • 实时云渲染平台 LarkXR:2D/3D 应用云推流的高效解决方案
  • 厦门市建设局网站摇号如何自己搭建一个企业网站
  • 郑州市科协网站游戏推广员到底犯不犯法
  • create_map外部函数
  • 中跃建设集团网站湖北省建设厅官方网站
  • 【028】乐器租赁管理系统
  • 散列文件的使用与分析
  • JavaEE初阶——多线程(6)定时器和线程池
  • 【Go语言爬虫】为什么要用Go语言写爬虫?
  • 网络安全培训
  • DNN 预测手术机器人姿态并做补偿包工程样本(2025.09)
  • 13. Qt 绘图-Graphics View
  • php构建网站如何开始展览设计
  • 金仓KingbaseES数据库:迁移、运维与成本优化的全面解析
  • AI推理硬件选型指南:CPU 与 GPU 的抉择
  • 手刃一个爬虫小案例
  • DMFNet代码讲解
  • 论文阅读:《A Universal Model for Human Mobility Prediction》
  • C++ ODR
  • 好看的网站颜色搭配制作网站高手
  • 手机端网站开发框架苏州专业网站seo推广
  • apimonitor工具使用