Skip to content

Commit 79df6e1

Browse files
authored
Create minimum-cost-to-buy-apples.py
1 parent 8b0eeab commit 79df6e1

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Python/minimum-cost-to-buy-apples.py

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Time: O(n * rlogn)
2+
# Space: O(n)
3+
4+
import itertools
5+
import heapq
6+
7+
8+
# dijkstra's algorithm
9+
class Solution(object):
10+
def minCost(self, n, roads, appleCost, k):
11+
"""
12+
:type n: int
13+
:type roads: List[List[int]]
14+
:type appleCost: List[int]
15+
:type k: int
16+
:rtype: List[int]
17+
"""
18+
def dijkstra(start):
19+
best = [float("inf")]*len(adj)
20+
best[start] = 0
21+
min_heap = [(0, start)]
22+
while min_heap:
23+
curr, u = heapq.heappop(min_heap)
24+
if best[u] < curr:
25+
continue
26+
for v, w in adj[u]:
27+
if best[v] <= curr+w:
28+
continue
29+
best[v] = curr+w
30+
heapq.heappush(min_heap, (curr+w, v))
31+
return best
32+
33+
adj = [[] for _ in xrange(n)]
34+
for a, b, c in roads:
35+
adj[a-1].append((b-1, c))
36+
adj[b-1].append((a-1, c))
37+
return [min(a+d*(k+1) for a, d in itertools.izip(appleCost, dijkstra(u))) for u in xrange(n)]

0 commit comments

Comments
 (0)