算法的阶梯

贪心算法---汽车加油问题

2018-10-31  本文已影响61人  Tedisaname
问题描述:

一辆汽车加满油后可行驶n公里。旅途中有若干个加油站。设计一个有效算法,指出应
在哪些加油站停靠加油,使沿途加油次数最少。对于给定的n(n <= 5000)和k(k <= 1000)个加油站位置,编程计算最少加油次数。并证明算法能产生一个最优解。

要求:

输入:第一行有2个正整数n和k,表示汽车加满油后可行驶n公里,且旅途中有k个加油站。接下来的1 行中,有k+1 个整数,表示第k个加油站与第k-1 个加油站之间的距离。第0 个加油站表示出发地,汽车已加满油。第k+1 个加油站表示目的地。
输出:输出编程计算出的最少加油次数。如果无法到达目的地,则输出”NoSolution”。

思路:

汽车行驶过程中,应走到自己能走到并且离自己最远的那个加油站,在那个加油站加油后再按照同样的方法贪心进行求解

具体算法:

先检测各加油站之间的距离,若发现其中有一个距离大于汽车加满油能跑的距离,则输出 "No Solution"
否则,对加油站间的距离进行逐个扫描,尽量选择往远处走,不能走了就让num++,最终统计出来的num便是最少的加油站数
例如:
输入:
7 7 //分别代表汽车加满油后能够行驶7公里,旅途中有7个加油站
1 2 3 4 5 1 6 6 //各个加油站直接的距离
输出:4 //输出的沿途能够到达目的地最少的加油次数

codes:

#include <iostream>
using namespace std;

void gasoline(int g[],int n,int k)
{
    int num = 0;
    for(int i = 0; i <= k; i++){
        if(g[i] > n)
            cout << "No Solution" << endl; //can not reach the destination, print the tip information
    }
    
    for(int i = 0,s = 0; i <= k; i++){//know if the g[i] can reach the destination
        s += g[i];  //accumulate the distance has been past
        if(s > n){  //if the accumalated distance better than the the car can reach ,need to gas
            num++;//count the numbers of the gas
            s = g[i];//reset the distance 
        }
        
    }
    
    cout << num << endl;//print out the number of the gas
}

int main()
{
    int n,k;//how far the car can go and how many gas stations there are
    int a[1000];
    cin >> n >> k;
    for(int i = 0; i <= k; i++ ){
        cin >> a[i];//the distance of each of the gas station input
    }
    
    gasoline(a,n,k);//can the fuction to count the result
    return 0;
}


//test:
7 7
1 2 3 4 5 1 6 6
4

--------------------------------
Process exited after 17.31 seconds with return value 0
请按任意键继续. . .
上一篇下一篇

猜你喜欢

热点阅读