[Leetcode]Some thoughts on Q134

Definitely not the best solution... Just some thoughts help myself to understand.


[Leetcode]Some thoughts on Q134_第1张图片

Let's define** P(i,j) as the probability that the train can leave station i for station j before run out of gas. In this problem, we know P should either be 1 (can arrive) or 0 (cannot arrive). Now the probability that we start from station 0, through N stations finally arrive station N is presented by P(0,N).
Now let station k be the station between station 0 and station N (0, then it is easy to see P(0,N)=P(0,k)P(k,N)
,which means as long as one interval is unachievable, the whole journey from station 0 to station N is unachievable.Now with the same reason, we could say if P(0,N)=0 due to P(k,N)=0, is also unachievable.In the other word, if station 0 cannot be the start point to station N due to the problematic point station k, then the station m between* station 0** and station k can also not be the start point. So the optimization way is we do not need to calculate the whole routine for each assumed start point, as long as we have a** start point, an end point and the problematic point k, we can directly reject all points from start point** to k point.
Now in this problem, assume there must be one achievable train routine, our choice is actually very limited. So by rejecting the enough choices, we could quickly find the answer.

[Leetcode]Some thoughts on Q134_第2张图片

Like the illustration above, we could simplify this problem as moving a rectangle of size N+1 with its starting point limited in area 0 to N. We calculate the sum from left to right, as long as the sum goes from positive to negative, for example, sum from 0 to z is positive, but from 0 to z+1 is negative, we could say P(0,z) suddenly goes to negative when becomes P(0,z+1). Since we have already proved that P(0,N)=P(0,k)P(k,N)*, so the only possibility causing the change from P(0,z)=1 to P(0,z+1)=0 is P(z,z+1)=0.So as we proved we could reject all the points from 0 to Z as starting points. Then we choose point z+1 as the new starting points and repeat the above process. Notice since the rectangle has size N+1, so we only need to check the sum of at most N+1 points.
Finally the first point we are unable to reject and is within first N+1 points is the answer. Otherwise, there is no such situation that train can travel all through. The complexity is O(n). ( n = number of the station).

class Solution {
public:
    int canCompleteCircuit(vector& gas, vector& cost) {
        int count=0;
        int sum=0;
        int start=0;
        int target_size=gas.size();
        for(int i=0;i

你可能感兴趣的:([Leetcode]Some thoughts on Q134)