Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the index in the circle such that a traveler can completes one round

I appeared in an interview. I stuck in one question. I am asking the same.

Question: There is circular road is given. That road contains number of petrol pumps. Each petrol pump have given amount of petrol. Distance between each two consecutive petrol pump is also given. Now there is a vehicle is given having empty fuel tank of limitless capacity. Build an algorithm so that vehicle can cover complete round without any backtracking. It is given that such path is definitely possible.

Input: (int fuel[], int distance[])

Output: petrol pump index from where vehicle can make complete round of circular road.

My approaches:

  1. Check from each petrol pump, if fuel tank is empty in between path, move to next petrol pump. and start the same process again. This algorithm takes O(N^2), here N = number of petrol pumps.

  2. Then I move to the Binary search concept, to reduce the complexity to O(n*logn). But I failed to conclude the solution. I messed up in this solution.

  3. Then I try to apply some intelligence, by choosing that petrol pump whose left petrol is maximum in between that two petrol pumps.

like image 732
devsda Avatar asked Nov 06 '12 19:11

devsda


1 Answers

(This may be equivalent to the algorithm Evgeny Kluev posted, which I don't understand. If so, that answer has priority.)

Let F_i_j be the net, signed amount of fuel in the tank on arriving at j having started at i with zero fuel in the tank before filling at i.

Calculate F_0_i for every node i by working around the circle adding fuel at each node and subtracting the fuel cost of each edge.

If F_0_0, the net fuel at the end of a circuit starting at 0, is negative, then there is not enough fuel in the system (this is not supposed to happen according to the problem statement).

If no F_0_i is negative, report 0 as result.

Otherwise, find the node s with the most negative value of F_0_s. Pick s as the starting node.

For any node i, F_s_i is equal to F_0_i + abs(F_0_s). Since F_0_s is the most negative F_0_i, that makes F_s_i non-negative.

Worked example, as suggested in a comment by Handcraftsman:
Label nodes 0 through 4

node: 0,1,2,3,4
fuel: 1,3,4,4,1
dist: 1,4,2,2,2


First calculate F_0_i for i = 1, 2, 3, 4, 0
Start at node 0 with 0 fuel.

f_0_1 = 0 + 1 - 1 = 0, min score 0, node 1;
f_0_2 = 0 + 3 - 4 = -1, min score -1, node 2;
f_0_3 = -1 + 4 - 2 = 1;
f_0_4 = 1 + 4 - 2 = 3;
f_0_0 = 3 + 1 - 2 = 2;

f_0_0 is non-negative, so there is enough fuel.

The minimum score was -1, at node 2, so the result is node 2.
like image 148
Patricia Shanahan Avatar answered Sep 25 '22 01:09

Patricia Shanahan