You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: gas_station.py
+78-6Lines changed: 78 additions & 6 deletions
Original file line number
Diff line number
Diff line change
@@ -11,18 +11,39 @@
11
11
from __future__ importdivision
12
12
importrandom
13
13
14
+
15
+
# We can use a Queue to store the current tour. We first enqueue first petrol pump to the queue, we keep enqueueing petrol pumps till we either complete the tour, or current amount of petrol becomes negative. If the amount becomes negative, then we keep dequeueing petrol pumps till the current amount becomes positive or queue becomes empty.
16
+
defgas_station(gas, cost):
17
+
n=len(gas)
18
+
start=0; next=1
19
+
Q= []
20
+
cur_gas=gas[start] -cost[start]
21
+
whilestart!=nextorcur_gas<0:
22
+
whilestart!=nextandcur_gas<0:
23
+
# pop, changing starting point
24
+
cur_gas-=gas[start] -cost[start]
25
+
start= (start+1)%n
26
+
ifstart==0: # go back to the first trial
27
+
return-1
28
+
cur_gas+=gas[next] -cost[next]
29
+
next= (next+1)%n
30
+
returnstart
31
+
32
+
33
+
'''
34
+
What if we want to keep the leftover gas as much as possible?
35
+
'''
14
36
# G(i,j) = the maximum leftover gas a car goes from i-th station to j-th.
15
37
# the car can use gas at i-th but not at j-th
16
38
# only valid when G(i,j) >= 0
17
39
# G(i,j) = max{G(i,mid)+G(k,mid) for i < mid < j,
18
40
# gas[i] - (cost[i]+...+cost[j])}
19
41
# We use G(i,i) for a circular route.
20
-
# ~ O(n^2)
21
-
defgas_station(gas, cost):
42
+
# ~ O(n^3)
43
+
defgas_station2(gas, cost):
22
44
n=len(gas)
23
45
G= {}
24
-
foriinrange(n):
25
-
G[i,(i+1)%n] =gas[i] -cost[i]
46
+
foriinrange(n): G[i,(i+1)%n] =gas[i] -cost[i]
26
47
printG
27
48
28
49
forkinrange(2,n+1):
@@ -45,9 +66,60 @@ def gas_station(gas, cost):
45
66
returnmax(circles.values()) >=0
46
67
47
68
69
+
'''
70
+
What if we want to get the trip with the minimum times of stops?
71
+
'''
72
+
# G(i,j,s) = maximum leftover gas from i-th to j-th station with s stops in-between; 0 <= s <= j-i-1
0 commit comments