1033. To Fill or Not to Fill (25)

贪婪(设装满油可跑的最大距离为s_max) 每到一个加油点的三种情况:
1.s_max内没有加油点,那么加满油跑s_max结束
2.s_max内有加油点,且有比当前加油点价格低的(选择最近的一个),则加油,车跑到那个加油点恰好没油
3.s_max内有加油点,但没有比当前加油点价格低的,那么选择价格最低的一个,加满油,跑到那个加油点
4.递归(1.2.3),提前结束或者到达终点

有个坑,第一个加油点(即距离为0)可能不存在,如果不考虑第二个测试点过不去
如果情况1打算用exit()退出的话,用exit(0),不能测试点会提示结果返回非零

#include<iostream>
#include<vector>
#include<algorithm>
#include<iomanip>
using namespace std;
double C, D, A, N,s_max;//s_max保存装满油可跑的最大距离
typedef struct station{
    double gas, price, length;
    station() { gas = 0;price = 0; }
    station(double x) { gas = 0;price = 0;length = x; }
    bool operator<(const station that) const
    {
        return this->length < that.length;
    }
}station;
vector<station> s;
double d=0, m=0;//d代表距离,m代表钱
int f_s(int index)
{
    int temp_index = index + 1;
    int v, flag = -1;
    double min = s[temp_index].price;
    while (temp_index <= (int)N && s[temp_index].length - s[index].length <= s_max)
    {
        if (s[temp_index].price <= s[index].price) { v = temp_index;    flag = 1;   break; }//s_max内出现比当前加油点价格低的
        if (s[temp_index].price <= min) { min = s[temp_index].price;    v = temp_index; flag = 0; }//选择s_max内加油点价格最低的一个
        temp_index++;
    }
    if (flag == -1) { d += s_max; return -1; }//s_max内没有加油点
    if (flag == 0)  {   d = s[v].length;    m += (C - s[index].gas) * s[index].price;   s[v].gas = C - (s[v].length - s[index].length) / A;}
    if (flag == 1) {    d = s[v].length;    m += ((s[v].length - s[index].length) / A - s[index].gas)*s[index].price;   s[v].gas = 0;   }
    return v;
}

int main()
{
    cin >> C >> D >> A >> N;
    s_max = C*A;
    for (int t = 0;t < N;t++)
    {
        station temp_station;
        cin >> temp_station.price >> temp_station.length;
        s.push_back(temp_station);
    }
    s.push_back(station(D));//加入终点
    sort(s.begin(), s.end());
    int index = 0;
    if (s[0].length != 0) index = -1;//特殊情况,开始点没有加油点
    while (index != N)
    {
        if (index == -1) break;
        index=f_s(index);

    }
    if (index == -1)
        cout << "The maximum travel distance = " << setprecision(2) << fixed << d << endl;
    else
        cout << setprecision(2) << fixed << m << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值