1. 程式人生 > 實用技巧 >1033 To Fill or Not to Fill (25分)貪心(???)

1033 To Fill or Not to Fill (25分)貪心(???)

題目

https://pintia.cn/problem-sets/994805342720868352/problems/994805458722734080

Sample Input 1:

50 1300 12 8
6.00 1250
7.00 600
7.00 150
7.10 0
7.20 200
7.50 400
7.30 1000
6.85 300

Sample Output 1:

749.17

code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

struct station{
    double D;
    double P;
};
vector<station>s;
bool cmp(station x,station y) {return x.D<y.D;}
int main()
{
    double Cmax,D,Davg;
    int N;
    cin>>Cmax>>D>>Davg>>N;
    station temp;
    for(int i=0;i<N;++i)
    {
        cin>>temp.P>>temp.D;
        s.push_back(temp);
    }
    sort(s.begin(),s.end(),cmp);
    if(s[0].D!=0) {
        printf("The maximum travel distance = 0.00\n");
        return 0;
    }
    double cost=0,C=0;

    for(int i=0;i<N;++i)
    {int tag=0;
        int a=-1,b=i+1;
        for(int j=i+1;j<N && Cmax*Davg>=s[j].D-s[i].D;++j)
        {
            tag=1;
            if(s[j].P<=s[i].P) {//找到了更便宜的站點
                a=j;
                cost+=((s[a].D-s[i].D)/Davg-C)*s[i].P;
                C=0;
                i=a-1;
                break;
            }
            if(s[j].P<s[b].P)
            {
                b=j;
            }
        }
        //找到了相對便宜的b站點
        if(a==-1 && Cmax*Davg>=D-s[i].D)//可以到目的地
        {
            cost+=((D-s[i].D)/Davg-C)*s[i].P;
            printf("%.2lf\n",cost);
            return 0;
        }
        if(a==-1 && tag)//加滿,去b站點
        {
            cost+=(Cmax-C)*s[i].P;
            C=Cmax-(s[b].D-s[i].D)/Davg;
            i=b-1;
        }
        else if(tag==0)//前面沒有加油站了
        {
            printf("The maximum travel distance = %.2lf\n",s[i].D+Cmax*Davg);
            return 0;
        }
    }
    return 0;
}