Recently I was asking about the algorithm to solve The Gas Station Problem and I got useful answer. Unfortunately solution with transforming a graph to complete graph and then preparing another one to find the shortest path (as described in paragraph 4) is really slow in case of my constraints.
I figured out how to implement much faster version. It's way better, but has a bottleneck :-(. Let me first describe my implementation. It's really simple:
I use BFS and relaxation method to calculate D[destination][0]:
D[v][f] - minimum cost to get from u to v with remaining f units of fuel at this city.
minFuel - minimum remaining fuel at v = max(0, f1 - distance(u,v))
maxFuel - maximum remaining fuel at v = tankCapacity - distance(u,v)
D[source][0] = 0
D[v][f] = min((u,v), f1, f2 | u->v in Edges and f1 in 0..tankCapacity and f2 in minFuel..maxFuel)
{ D[u][f1] + (f2 - f1 + distance(u,v)) * fuelRate[u] }
The bottleneck is because of going through all possible values (f1, f2).
Pseudocode:
queue.push(source);
D[source][0] = 0
visited[source] = true
while(!queue.empty)
current = queue.pop
foreach (current,v) in Edges
if !visited[v]
queue.push(v)
visited[v] = true
for f1 in 0..tankCapacity
if D[current][f1] == infinity
continue
minFuel = max(0, f1 - distance[current,v])
maxFuel = tankCapacity - distance[current,v]
for f2 in minFuel..maxFuel
toRefill = f2 - f1 + distance[current,v]
newCost = D[current][f1] + toRefill * fuelRate[current]
if (newCost < D[v][f2])
D[v][f2] = newCost
return D[destination][0]
Constraints (only integers):
maximum vertices: 1000
maximum edges: 10000
maximum distance: 100
maximum fuel rate: 100
maximum tank capacity: 100
Does anybody have an idea how to improve this algorithm to make it faster?