卡码网题目链接
https://kamacoder.com/problempage.php?pid=1152
https://kamacoder.com/problempage.php?pid=1153
https://kamacoder.com/problempage.php?pid=1154
题解
94.城市间货物运输I
和昨天那题思路类似,加了个队列优化,仿照着c++代码写的。
95.城市间货物运输II
具体看题解,代码也是仿照题解写的。
96.城市间货物运输III
看题解的感悟:理解思路挺重要,还有了4个拓展,联系了前几天的算法。
代码部分:要加updated更新记录,防止时间超限,题解也是这么写的
代码
python
#94.城市间货物运输I
from collections import deque
class Edge():
def __init__(self, to, val):
self.to = to
self.val = val
if __name__ == "__main__":
n, m = map(int, input().split())
graph = [[] for _ in range(n + 1)]
isInQueue = [False] * (n + 1)
for _ in range(m):
s, t, v = map(int, input().split())
graph[s].append(Edge(t, v))
start = 1
end = n
minDist = [float('inf')] * (n + 1)
minDist[start] = 0
queue = deque()
queue.append(start)
isInQueue[start] = True
while queue:
node = queue.popleft()
isInQueue[node] = False
for edge in graph[node]:
fromm, to, val = node, edge.to, edge.val
if minDist[to] > minDist[fromm] + val:
minDist[to] = minDist[fromm] + val
if isInQueue[to] == False:
queue.append(to)
isInQueue[to] = True
if minDist[end] == float('inf'):
print("unconnected")
else:
print(minDist[end])
python
#95.城市间货物运输II
if __name__ == "__main__":
n, m = map(int, input().split())
graph = []
for _ in range(m):
graph.append(list(map(int, input().split())))
minDist = [float('inf')] * (n + 1)
start, end = 1, n
minDist[start] = 0
flag = False
for i in range(1, n + 1): # 多循环一次
for side in graph:
fromm, to, val = side[0], side[1], side[2]
if i < n:
if minDist[fromm] != float('inf') and minDist[to] > minDist[fromm] + val:
minDist[to] = minDist[fromm] + val
else:
if minDist[fromm] != float('inf') and minDist[to] > minDist[fromm] + val:
flag = True
if flag:
print("circle")
elif minDist[end] == float('inf'):
print("unconnected")
else:
print(minDist[end])
python
#96.城市间货物运输III
if __name__ == "__main__":
n, m = map(int, input().split())
graph = []
for _ in range(m):
graph.append(list(map(int, input().split())))
src, dst, k = map(int, input().split())
minDist = [float('inf')] * (n + 1)
minDist[src] = 0
for i in range(k + 1):
updated = False
minDist_copy = minDist.copy()
for side in graph:
fromm, to, val = side[0], side[1], side[2]
if minDist_copy[fromm] != float('inf') and minDist[to] > minDist_copy[fromm] + val:
minDist[to] = minDist_copy[fromm] + val
updated = True
if not updated:
break
if minDist[dst] == float('inf'):
print("unreachable")
else:
print(minDist[dst])