See 两种 Dijkstra 写法(附题单)Python/Java/C++/Go/JS/Rust.

743. Network Delay Time

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
g = [[] for _ in range(n)]
for x, y, d in times:
g[x - 1].append((y - 1, d))
dis = [inf] * n
dis[k - 1] = 0
h = [(0, k - 1)]
while h:
dx, x = heappop(h)
if dx > dis[x]:
continue
for y, d in g[x]:
new_dis = dx + d
if new_dis < dis[y]:
dis[y] = new_dis
heappush(h, (new_dis, y))
mx = max(dis)
return mx if mx < inf else -1
Read more »

See 线性 DP,附相似题目(Python/Java/C++/Go)

2830. Maximize the Profit as the Salesman

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def maximizeTheProfit(self, n: int, offers: List[List[int]]) -> int:
groups = [[] for _ in range(n)]
for start, end, gold in offers:
groups[end].append((start, gold))
f = [0] * (n + 1)
for end, g in enumerate(groups):
f[end + 1] = f[end]
for start, gold in g:
f[end + 1] = max(f[end + 1], f[start] + gold)
return f[n]

2008. Maximum Earnings From Taxi

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def maxTaxiEarnings(self, n: int, rides: List[List[int]]) -> int:
groups = [[] for _ in range(n)]
for start, end, tip in rides:
groups[end - 1].append((start - 1, end - start + tip))
f = [0] * (n + 1)
for end, g in enumerate(groups):
f[end + 1] = f[end]
for start, profit in g:
f[end + 1] = max(f[end + 1], f[start + 1] + profit)
return f[n]
Read more »
0%