suggest an algorithm for the following puzzle!
There are n petrol bunks arranged in circle. Each bunk is separated from the rest by a certain distance. You choose some mode of travel which needs 1litre of petrol to cover 1km distance. You can't infinitely draw any amount of petrol from each bunk as each bunk has some limited pe开发者_高级运维trol only. But you know that the sum of litres of petrol in all the bunks is equal to the distance to be covered.
ie let P1, P2, ... Pn be n bunks arranged circularly. d1 is distance between p1 and p2, d2 is distance between p2 and p3. dn is distance between pn and p1.Now find out the bunk from where the travel can be started such that your mode of travel never runs out of fuel.
There is an O(n) algorithm.
Assume v[0] = p1 - d1, v[1] = p2 - d2, ... , v[n-1] = pn - dn. All we need to do is finding a starting point i, such that all the partial sum is no less than 0, i.e., v[i] >= 0, v[i] + v[(i+1)%n] >= 0, v[i] + v[(i+1)%n] + v[(i+2)%n] >= 0, ..., v[i]+...+v[(i+n-1)%n] >= 0.
We can find such a start point by calculating s[0] = v[0], s[1] = v[0]+v[1], s[2] = v[0]+v[1]+v[2], ..., s[n-1] = v[0] + ... + v[n-1], and pick up the minimum s[k]. Then the index (k+1)%n is the start point.
Proof: Assume the minimum element is s[k]. By the problem description, there must be the minimum s[k] <= 0.
Because the total sum v[0] + v[1] + ... + v[n-1] = 0, we have v[k+1] + v[k+2] + ... v[n-1] = -s[k] >= 0, and it is impossible that v[k+1] + ... v[j] < 0 (k < j < n). (Because if v[k+1] + ... v[j] < 0, then s[j] < s[k], which is contradictory with the assumption that s[k] is minimum.) So we have v[k+1] >= 0, v[k+1] + v[k+2] >= 0, ..., v[k+1] + v[k+2] + ... + v[n-1] >= 0.
Because s[k] is the minimum one, We also have v[k+1] + v[k+2] + ... + v[n-1] + v[0] = -s[k] + v[0] = -s[k] + s[0] >= 0, -s[k] + v[0] + v[1] = -s[k] + s[1] >= 0, ..., -s[k] + v[0] + v[1] + ... + v[k-1] = -s[k] + s[k-1] >= 0. So all the parital sum starting from (k+1) is no less than 0. QED.
Let's choose a junk algorithm that we know is wrong to see why it is wrong...
Notation...
Current Point: (gallons of gas at Current Point, gallons required to make next point)-> Remaining Gas (gallons)
In a little more mathematical form:
P[i]: (g(P[i]), d(P[i+1])) -> sum of (g(P[i]) - d(P[i+1])) from i=1 to current point-1
(And now for the bad algorithm...)
P1: (2,2) -> 0 (at P2)
P2: (5,3) -> 2 (at P3)
P3: (2,4) -> 0 (at P4)
P4: (2,5) -> -3 (ran out of gas 3 miles short of P5)
In order to make it to P5, we have to have three extra gallons of gas by the time we make it to P3, and in order to have 3 extra gallons at P3, we need to have 3 extra gallons at P1:
??? -> +3 (at P1)
P1: (2,2) -> 0+3 = 3 (at P2)
P2: (5,3) -> 2+3 = 5 (at P3)
P3: (2,4) -> 0+3 = 3 (at P4)
P4: (2,5) -> -3 +3 = 0 (made it to P5)
The trick, therefore, is to find the very worst sections -- where you are not given enough gas to traverse them. We know we can't start from P4, P3, P2, or P1. We have to start somewhere earlier and save up enough gas to make it through the bad section.
There will no doubt be multiple bad sections within the circle, making this somewhat complicated, but it's actually quite easy to figure out how to do this.
It's possible that the next few points following the very worst stretch in the circle could be traveled after the stretch, but only if they make no changes to your gas reserves. (e.g. the point after the worst stretch gives you 2 gallons of gas and makes you go 2 gallons of distance to the next point.)
In some cases, however, the worst section MUST be covered last. That's because before you start on that section, you need as much gas saved up as possible, and the next point after the worst stretch might give you the very last bit of gas that you need, which means you need to traverse it prior to taking on the worst stretch. Although there may exist multiple solutions, the simple fact of the matter is that traversing the worst section last is ALWAYS a solution. Here's some code:
class point_ {
int gasGiven_;
int distanceToNextPoint_;
public:
int gasGiven() {return gasGiven_;}
int distanceToNextPoint {return distanceToNextPoint_;}
}
class Circle_ {
public:
numberOfPoints;
point_ *P;
}
In main():
int indexWorstSection=0;
int numberPointsWorstSection=0;
int worstSum=0;
int currentSum=0;
int i=0;
int startingPoint =0;
// construct the circle, set *P to malloc of numberOfPoints point_'s, fill in all data
while (i<(Circle.numberOfPoints-1) || currentSum<0)
{
currentSum += Circle.P[i].gasGiven() - Circle.P[i].distanceToNextPoint();
if (currentSum < worstSum) { worstSum = currentSum; indexWorstSection=i-numberPointsWorstSection; startingPoint=i;}
if (currentSum>0) { currentSum=0; }
else { numberPointsWorstSection++; }
if (i==(Circle.numberOfPoints-1)) { i=0; }
else { i++; }
}
if (indexWorstSection<0) indexWorstSection=Circle.numberOfPoints+indexWorstSection;
The reason why you can't make it a for-loop is because the worst section might be, for example, from i=(Circle.numberOfPoints -2) to i=3. If the currentSum is under zero, it must continue back at the start of the array.
Haven't tried the code and haven't done any serious programming in almost a decade. Sorry if it has some bugs. You will no doubt have to clean this up a bit.
This does what several of the other answers do - finds the minimum of the "graph" created by the net-change-in-petrol deltas as you circle around. Depending on where we start, the exact values may be moved uniformly upwards or downwards compared to some other starting position, but the index of the minimal value is always a meaningful indication of where we can start and know we'll never run out of petrol. This implementation tries to minimise memory use and completes in O(n).
#include <iostream>
int dist[] = { 3, 10, 2, 4, 6, 9 };
int refill[] = { 3, 4, 6, 3, 7, 11 };
static const int n = sizeof dist / sizeof *dist;
int main()
{
int cum = 0, min = 0, min_index = 0;
for (int i = 0; i < n; ++i)
{
cum += refill[i] - dist[i];
std::cout << cum << ' ';
if (cum <= min)
{
min = cum;
min_index = i;
}
}
std::cout << "\nstart from index " << (min_index + 1) % n << " (0-based)\n";
}
See it running on ideone.com
Here's an approach that works in O(n)
time and O(1)
space. Start at any station, call it station 0
, and advance until you run out of gas. If you don't run out of gas, done. Otherwise, if you run out between stations k
and k+1
, start over again at station k+1
. Make a note if you pass 0
again, and if you run out after that it can't be done.
The reason this works is because if you start at station i
and run out of gas between stations k
and k+1
, then you will also run out of gas before station k+1
if you start at any station between i
and k
.
Here's an algorithm, given an arrays P
(petrol) and D
(distance):
int position = 0;
int petrol = P[0];
int distance = D[0];
int start = 0;
while (start < n) {
while (petrol >= distance) {
petrol += P[++position % N] - distance;
distance = D[position % N];
if (position % N == start)
return start;
}
start = position;
petrol = P[start];
}
return -1;
Each leg of the trip has a net effect on fuel, adding from storage and using to make the trip. All you need to do is loop through once, keeping track of your fuel level when you arrive at each point, even if it is negative. Keep track of the lowest fuel level and which point it occurred on. If you start at that point, you will be able to make it around from there without running out of fuel. This assumes that you start with an empty tank and only get gas from the place you are starting, also that you can always take all the gas, you won't ever get full and have to leave gas behind.
Let's say you have 5 points, P1 to P5:
Point Fuel Distance to next point
P1 5 8
P2 3 4
P3 12 7
P4 1 4
P5 7 5
If you choose P1, then load up on 5 fuel, travelling to P2 leaves you with -3 fuel. Going on you get these numbers:
Point Fuel Balance (before refueling)
P1 0
P2 -3
P3 -4
P4 1
P5 -2
P1 0
So if you start at the lowest value, P3, you can make it back around (fuel 0 to start, 5 at P4, 2 at P5, 4 at P1, 1 at P2, 0 back at P3)
float [] storedFuel = { 1, 1, 1, 1, 1, 1 };
float [] distance = { 1, 1, 1, 1, 1, 1 };
int n = 6;
int FindMinimumPosition()
{
float fuel = 1;
int position = 0;
float minimumFuel = 1;
int minimumPosition = 0;
while (position < n)
{
fuel += storedFuel[position];
fuel -= distance[position];
position++; // could be n which is past array bounds
if (fuel < minimumFuel) {
minimumFuel = fuel;
minimumPosition = position % n;
}
}
return minimumPosition
}
Off the top of my head, here's an algorithm that should work:
- let e1 = (the amount of petrol in P1) - d1 (i.e., the excess petrol in P1 over what is needed to travel to P2), and similarly for e2, ..., en. (These numbers can be positive or negative.)
- Form the partial sums s1 = e1; s2 = e1 + e2; ..., sn = e1 + e2 + ... + en. We know from the conditions of the problem that sn = 0.
The problem now is to find a circular permutation of the bunks (or, more simply, of the e values) so that none of the s values are negative. One can simply repeatedly shift one, updating the s values, until a solution is found. (It's not immediately obvious that there is always a solution, but I think there is. If you shift n times without finding a solution, then you're guaranteed that there is none.)
This is an O(n^2) algorithm--not very good. A good heuristic (possibly an exact solution) may be to shift so that the largest-magnitude negative s value is shifted to position n.
For each gap, find the profit or loss earned by filling up at the bunk before the gap, and then crossing the gap. At an arbitrary point work out total amount of petrol remaining at each point of a complete circle, accepting that it may be negative at some point.
Now repeatedly circularly shift that solution. Remove the information for the last point, which will now be the first point. Set up an offset to take account of the fact that you are now starting one point further back, and will more (or less) petrol at each remaining point. Add in information for the new point, taking account of the offset. This solution is feasible if the minimum amount of petrol at any point, plus the offset, is greater than zero.
You can use some sort of log n data structure (sorted map, priority queue...) to keep track of the minimum so this takes the cost down to n log n.
Here is an O(n) solution
private int findStartingPoint(int[] petrol, int[] dist, int[] mileage){
int curPoint = 0;
boolean done = false;
while(curPoint < petrol.length && !done)
{
int prevPoint = curPoint;
int nextPoint = (curPoint+1) % petrol.length;
int nextSolutionPoint = curPoint + 1;
int totalPetrol = 0;
while(nextPoint != curPoint){
totalPetrol += petrol[prevPoint] - (dist[prevPoint]/mileage[prevPoint]);
if(totalPetrol < 0){
curPoint = nextSolutionPoint;
break;
}
prevPoint = nextPoint;
nextPoint = (nextPoint + 1) % petrol.length;
nextSolutionPoint++;
}
if(curPoint == nextPoint){
return curPoint;
}
}
return -1;
}
}
精彩评论