"Gas station" CPP

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.