题解 | #To Fill or Not to Fill#

To Fill or Not to Fill

https://www.nowcoder.com/practice/f7eba38f7cd24c45982831e0f38518f9

区间贪心算法,后一个区间的起点较前一区间偏移多少,区间终点也会偏移多少,所以不用考虑油箱容积的变化。另外浮点数需使用double,float不能通过测试。

#include <iostream>
#include <algorithm>
using namespace std;
struct station {
    double price;
    int distance;
};
bool compare(station a, station b) {
    return a.price <= b.price;
}
int main() {
    int cmax, d, davg, n;
    while (cin >> cmax >> d >> davg >> n) { // 注意 while 处理多个 case
        // cout << a + b << endl;
        station stationList[n];
        for (int i = 0; i < n; i++) {
            cin >> stationList[i].price >> stationList[i].distance;
        }
        sort(stationList, stationList + n, compare);
        bool way[d + 1];
        for (int i = 0; i < d + 1; i++) way[i] = false;
        int farest = cmax * davg;
        double price = 0;
//从油价最低的加油站开始,尽肯能多的去规划里程
        for (auto station : stationList) {
            int distance = 0;
            for (int j = station.distance + 1; j <= d &&
                    j <= station.distance + farest; j++) {
                if (way[j] == false) {
                    way[j] = true;
                    distance++;
                }  
            }
            price += distance / (davg * 1.0)* station.price;
        }
        bool finish = true;
        double allDistance = 0;
        for (int i = 1; i < d+ 1; i++) {
            if (way[i] == false) {
                finish = false;
                break;
            } else allDistance++;
        }
        if (finish == true) printf("%.2f\n", price);
        else printf("The maximum travel distance = %.2f\n", allDistance);
    }
}
// 64 位输出请用 printf("%lld")// 64 位输出请用 printf("%lld")

全部评论

相关推荐

AI牛可乐:哇,听起来你遇到了什么挑战呢!🐮牛可乐在这里,虽然小,但是勇敢又聪明,想听听你的具体情况哦!如果你愿意的话,可以点击我的头像给我私信,我们可以一起想办法应对挑战,好不好呀?🌟🎉
点赞 评论 收藏
分享
牛客868257804号:九个中铁八个中建
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务