Leetcode | Gas Station

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an 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.

这道题也是做不出来。思路并没有错,只是中间有些证明并没有想清楚,所以一直卡住。google了一下,解题的详细思路如下:

  1. If car starts at A and can not reach B. Any station between A and B can not reach B.(B is the first station that A can not reach.)
  2. If the total number of gas is bigger than the total number of cost. There must be a solution.

证明: 1. 这里用left[i...j]来表示在从i到j累计剩下的油,也就是left[i...j]=(gas[i]-cost[i]) + ... _ (gas[j]-cost[j])。不能到达B,说明left[A...B]<0。也就是说,left[A...B-1]>0 but left[A...B-1] + (gas[B]-cost[B]) < 0,所以gas[B]-cost[B]<0,B也不是解。

注意从A能够到达B-1,所以left[A...i] > 0, A <= i < B。假设我们从一个新的位置C(A <= C <B)重新出发,已知 0< left[A...B-1]=left[A...C-1]+left[C...B-1]且left[A...C-1]>0,那么我们有left[C...B-1]<left[A...B-1]。因为left[A...B-1] + (gas[B]-cost[B]) < 0,所以left[C...B-1] + (gas[B]-cost[B]) < 0,也就是C也不能到达B。证毕。因此只能从B+1重新开始。

2. 反证法即可。假设不存在解,那么对于所有的0<=k<N,left[k...N-1,0...k-1]<0。但是由题设left[0...N-1]>0,矛盾。于是一定存在解。

于是,我们可以统计总的left,如果<0,无解。

否则,从每个位置i开始,看它能不能到达N-1,当它不能到达某个位置B时,也就是left[i...B]<0时,ii到B都不是解。我们从B+1继续搜索。最后一个cadidate一定就是解。

 1 class Solution {
 2 public:
 3     int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
 4         int n = gas.size();
 5         int j = -1, sum = 0, total = 0;
 6         for (int i = 0; i < n; ++i) {
 7            sum += gas[i] - cost[i];
 8            total += gas[i] - cost[i];
 9            if (sum < 0) {
10                j = i;
11                sum = 0;
12            }
13         }
14         if (total < 0) return -1;
15         else return j + 1;
16     }
17 };

 

posted @ 2014-04-27 00:27  linyx  阅读(173)  评论(0编辑  收藏  举报