【代码随想录算法训练营——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])
