1033. To Fill or Not to Fill (25)

来源:互联网 发布:滨波品牌什么档次知乎 编辑:程序博客网 时间:2024/05/23 00:16

贪婪(设装满油可跑的最大距离为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;}
0 0
原创粉丝点击