卡码网题目链接
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])