1033 To Fill or Not to Fill (25分)

Posted d-i-p

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1033 To Fill or Not to Fill (25分)相关的知识,希望对你有一定的参考价值。

1. 题目

技术图片

2. 思路

  1. 把终点作为price=0, distance=d的点插入
  2. 按照distance排序
  3. 如果distance + c*davg内有station,找最近的比当前价格低的,买能恰好到达的gas,如果价格都高,买其中最低的,买满油
  4. 如果distance + cdavg内没有station, 输出当前distance + cdavg

3. 注意点

  1. 要设置当前油量的变量,可能不是0
  2. 如果distance=0没有station, 输出0

4. tip

巧妙把最后d最为station插入, 减少了很多的讨论,使得代码变得简单,启发是看有些特殊情况能不能化为一般情况

5. 代码

#include<cstdio>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<iostream> 

// 21:51 - 23:12
using namespace std;

struct station{
    double price;
    double distance;
    station(double price, double distance){
        this->price = price;
        this->distance = distance;
    }
};

double c, d, davg;
int n;
vector<station> s;

bool cmp(station a, station b){
    return a.distance < b.distance;
}

int main(){
    scanf("%lf %lf %lf %d", &c, &d, &davg, &n);
    for(int i=0;i<n;i++){
        double price, distance;
        scanf("%lf %lf", &price, &distance);
        s.push_back(station(price, distance));
    }
    s.push_back(station(0, d));
    n++;
    sort(s.begin(), s.end(), cmp);
    if(s[0].distance != 0){
        printf("The maximum travel distance = 0.00");
        return 0;
    }
    
    double sum = 0;
    double now_c = 0;
    
    int i = 0;
    int pos = 0;
    double dis = c*davg; //一次最远距离 
    while(1){
        int index = -1;
        double min_price = 0x7fffffff;
        for(i=pos+1;i<n && s[i].distance-s[pos].distance<=dis;i++){
            if(s[i].price < s[pos].price){
                index = i;
                break;
            }
            if(s[i].price < min_price){
                min_price = s[i].price;
                index = i;
            }
        }
        if(i == n){
            printf("%.2f", sum);
            break;
        }
        if(index == -1){
            printf("The maximum travel distance = %.2f", s[pos].distance + dis);
            return 0;
        }
        if(s[pos].price < s[index].price){
            double need = (s[index].distance - s[pos].distance) / davg;
            sum += (c - now_c)*s[pos].price;
            now_c = c - need;
        }else{
            double need = (s[index].distance - s[pos].distance) / davg;
            if(need > now_c){
                sum += (need - now_c) * s[pos].price;
            }
            now_c = 0;
        }
        pos = index;
    }
}

以上是关于1033 To Fill or Not to Fill (25分)的主要内容,如果未能解决你的问题,请参考以下文章

PAT 1033. To Fill or Not to Fill

1033 To Fill or Not to Fill (25 分)

1033. To Fill or Not to Fill (25)

1033 to fill or not to fill

PAT 1033 To Fill or Not to Fill[dp]

1033. To Fill or Not to Fill (25)