title :
There was N gas stations along a circular route, where the amount of gas at Station I was gas[i] .
You had a car with an unlimited gas tank and it costs of gas to travel from station cost[i] I to its next station (i+ 1). You begin the journey with a empty tank at one of the gas stations.
Return The starting gas station's index If you can travel around the circuit once, otherwise return-1.
Note:
The solution is guaranteed to be unique.
Code :
classSolution { Public: intCancompletecircuit (vector<int>& Gas, vector<int>&Cost ) { if(Gas.size ()! = Cost.size ())return-1; intStart_station =-1; intTmp_sum =0; intTotal =0; for(size_t i =0; I < gas.size (); ++i) {tmp_sum+ = Gas[i]-Cost[i]; Total+ = Gas[i]-Cost[i]; if(tmp_sum<0) {tmp_sum=0; Start_station=i; } } returntotal>=0? start_station+1: -1; }};
Tips:
1. Adopt the idea of greedy algorithm: maintain a tmp_sum, calculate the difference from the start node to the current node loss, if less than 0, then discard directly; otherwise, continue to accumulate.
2. Final judgment on the completion of the itinerary, need to maintain a total: if all is greater than or equal to 0, then the decision must be able to go through the journey. What is this for? Specific principles can be found in the pigeon nest principle.
Resources
greedy algorithm : http://zh.wikipedia.org/wiki/greedy method
Pigeon Nest principle : http://zh.wikipedia.org/wiki/pigeons Nest principle
"Gas station" CPP