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.
Hide Tags: Greedy
题目:循环一圈的道路上有gasSize个加气站gas[gasSize],从i到i+1加气站需要耗费cost[i]的气,要求可以从其中任意一个加气站出发,只要能保证回到出发点。
思路:贪恋算法。
第一次循环:从gas[0]加气站出发i 从0-> gasSize-1, 挨站判断是否能到第i站,over 为每到一站后剩余的燃气,over 为负数说明骑车到不了当前站i,当发现到不了的情况后当前站,马上就将当前站i作为出发点,over清零,重新开始向前走。
第二次循环:当然有可能走完一圈后还不能判断的,因为有可能起点并不是gas[0],所以还需要继续向前走,直到gas[start ],期只要有出现到不了的情况这判断为-1。如果能到最后判断over是否大于0,大于0则说明能到,否则返回-1。
int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize) {
int i = 0;
int over = gas[0];
int start = 0;
if(gasSize == 1) return (gas[0] >= cost[0]) ? 0 : -1;
for(i=1;i<gasSize;i++)
{
over = over - cost[i-1];
if(over < 0)
{
start = i;
over = 0;
}
over = over + gas[i];
}
over = over - cost[gasSize-1];
for(i=0;i<start;i++)
{
if(over < 0)
{
return -1;
}
over = over + gas[i] - cost[i];
}
return (over >= 0) ? start : -1 ;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/xiabodan/article/details/47008423