一个汽车加满油后可以行使n千米,图中会经过一系列加油站,求到达最终加油的最少次数,给出每个加油站之间的距离。
#include<stdio.h>
#define n 7//n表示汽车加满油后可以行使nkm
int main()
{
int a[n + 1] = {1,2,3,4,5,1,6,6};
int k = 7;//k表示途中有k个加油站
int rest = 7;//油箱里的剩余油量,在起点时油量是满的
int count = 0;
int i = 0;
//n表示加满油可以行使n千米
while(i < n + 1){
//当前行程>rest
if(a[i] > rest){
//加油
count ++;
//重新赋值rest
rest = n;
}
rest -= a[i];
printf("rest=%d,i=%d\n",rest,i);
i ++;
}
printf("the mininum is %d.",count);
return 0;
}
每到一个加油站时,判断当前的油量能否开到下一个加油站,再决定是否加油,i表示对应的加油站。贪心算法:局部最优能推导出整体最优,很容易,算法思维很常态化。
代码地址:https://github.com/jingong/Algorithm/blob/master/4.贪心算法/汽车加油问题.txt