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