Skip to content

Commit 45bea5b

Browse files
committed
Time: 1644 ms (11.59%), Space: 48.3 MB (47.83%) - LeetHub
1 parent fac4459 commit 45bea5b

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# time complexity: O((n*k + e)log(n*k))
2+
# space complexity: O(n*k + e)
3+
import heapq
4+
from typing import List
5+
6+
7+
class Solution:
8+
def minimumCost(self, n: int, highways: List[List[int]], discounts: int) -> int:
9+
graph = [[] for _ in range(n)]
10+
for highway in highways:
11+
u, v, toll = highway
12+
graph[u].append((v, toll))
13+
graph[v].append((u, toll))
14+
pq = [(0, 0, 0)]
15+
dist = [[float("inf")] * (discounts + 1) for _ in range(n)]
16+
dist[0][0] = 0
17+
visited = [[False] * (discounts + 1) for _ in range(n)]
18+
while pq:
19+
currentCost, city, discountsUsed = heapq.heappop(pq)
20+
if visited[city][discountsUsed]:
21+
continue
22+
visited[city][discountsUsed] = True
23+
for neighbor, toll in graph[city]:
24+
if currentCost + toll < dist[neighbor][discountsUsed]:
25+
dist[neighbor][discountsUsed] = currentCost + toll
26+
heapq.heappush(
27+
pq, (dist[neighbor][discountsUsed], neighbor, discountsUsed))
28+
29+
if discountsUsed < discounts:
30+
newCostWithDiscount = currentCost + toll // 2
31+
if (newCostWithDiscount < dist[neighbor][discountsUsed + 1]):
32+
dist[neighbor][
33+
discountsUsed + 1
34+
] = newCostWithDiscount
35+
heapq.heappush(
36+
pq, (newCostWithDiscount, neighbor, discountsUsed + 1))
37+
38+
minCost = min(dist[n - 1])
39+
return -1 if minCost == float("inf") else minCost
40+
41+
42+
n = 5
43+
highways = [[0, 1, 4], [2, 1, 3], [1, 4, 11], [3, 2, 3], [3, 4, 2]]
44+
discounts = 1
45+
print(Solution().minimumCost(n, highways, discounts))

0 commit comments

Comments
 (0)