Skip to content

Commit 417c326

Browse files
authored
Create minimum-cost-to-reach-city-with-discounts.py
1 parent 0e3a91b commit 417c326

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Time: O((|E| + |V|) * log|V|) = O(|E| * log|V|) by using binary heap,
2+
# if we can further to use Fibonacci heap, it would be O(|E| + |V| * log|V|)
3+
# Space: O(|E| + |V|) = O(|E|)
4+
5+
import collections
6+
import heapq
7+
8+
9+
class Solution(object):
10+
def minimumCost(self, n, highways, discounts):
11+
"""
12+
:type n: int
13+
:type highways: List[List[int]]
14+
:type discounts: int
15+
:rtype: int
16+
"""
17+
adj = [[] for _ in xrange(n)]
18+
for u, v, w in highways:
19+
adj[u].append((v, w))
20+
adj[v].append((u, w))
21+
src, dst = 0, n-1
22+
best = collections.defaultdict(lambda: collections.defaultdict(lambda: float("inf")))
23+
best[src][discounts] = 0
24+
min_heap = [(0, src, discounts)]
25+
while min_heap:
26+
result, u, k = heapq.heappop(min_heap)
27+
if best[u][k] < result:
28+
continue
29+
if u == dst:
30+
return result
31+
for v, w in adj[u]:
32+
if result+w < best[v][k]:
33+
best[v][k] = result+w
34+
heapq.heappush(min_heap, (result+w, v, k))
35+
if k > 0 and result+w//2 < best[v][k-1]:
36+
best[v][k-1] = result+w//2
37+
heapq.heappush(min_heap, (result+w//2, v, k-1))
38+
return -1

0 commit comments

Comments
 (0)