朴素Dijkstra:743. 网络延迟时间
以最佳节点为状态
import collections
import heapq
class Solution:
def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:
relation = collections.defaultdict(list)
for [u, v, w] in times:
relation[u].append((v, w))
dijq = [(0, k)]
dist = {}
while dijq:
d, u = heapq.heappop(dijq)
if u in dist:
continue
dist[u] = d
for v, w in relation[u]:
if not (v in dist):
heapq.heappush(dijq, (d + w, v))
return max(dist.values()) if len(dist) == n else -1
if __name__ == "__main__":
print(Solution().networkDelayTime(times = [[2,1,1],[2,3,1],[3,4,1]], n = 4, k = 2))
print(Solution().networkDelayTime(times = [[1,2,1]], n = 2, k = 1))
print(Solution().networkDelayTime(times = [[1,2,1]], n = 2, k = 2))
有限制的最短路径 1928. 规定时间内到达终点的最小花费
以限制条件作为状态
import collections
class Solution:
def minCost(self, maxTime: int, edges: list[list[int]], passingFees: list[int]) -> int:
n = len(passingFees)
f = [[float("inf")] * n for _ in range(maxTime + 1)]
f[0][0] = passingFees[0]
for t in range(1, maxTime + 1):
for x, y, dt in edges:
if dt <= t:
f[t][x] = min(f[t][x], f[t-dt][y] + passingFees[x])
f[t][y] = min(f[t][y], f[t-dt][x] + passingFees[y])
ans = min(f[t][n-1] for t in range(0, maxTime + 1))
return ans if ans < float("inf") else -1