题解:P1016 [NOIP 1999 普及组/提高组] 旅行家的预算

· · 题解

P1016 [NOIP 1999 普及组/提高组] 旅行家的预算

感觉新的 hack 数据好毒瘤。

思路

考虑贪心,很显然对于每个加油站 i,我们有以下几种选择:

实现

注意处理精度问题。

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
//十年OI一场空,不开long long见祖宗
const double eps = 1e-8;
struct station{
    double dist;
    double price;
    bool operator < (const station &rhs) const{
        return dist < rhs.dist;
    }
}sta[10];
double s , c , l , p0;
int N;
int main(){
    scanf("%lf%lf%lf%lf%d" , &s , &c , &l , &p0 , &N);
    sta[0].dist = 0.0;
    sta[0].price = p0;
    for(int i = 1 ; i <= N ; ++i){
        double d , p;
        scanf("%lf%lf" , &d , &p);
        sta[i].dist = d;
        sta[i].price = p;
    }
    sta[N + 1].dist = s;
    sta[N + 1].price = 0.0;
    sort(sta , sta + N + 2);
    double res = c * l;
    for(int i = 0 ; i <= N ; ++i){
        if(sta[i + 1].dist - sta[i].dist > res + eps){
            printf("No Solution");
            return 0;
        }
    }
    double cur_ = 0.0 , tot = 0.0;
    int cur = 0;
    while(cur <= N){
        int cheap = -1;
        for(int i = cur + 1 ; i <= N + 1 && sta[i].dist - sta[cur].dist <= res + eps ; ++i){
            if(sta[i].price < sta[cur].price - eps){
                cheap = i;
                break;
            }
        }
        if(cheap != -1){
            double need = (sta[cheap].dist - sta[cur].dist) / l;
            if(cur_ < need){
                tot += (need - cur_) * sta[cur].price;
                cur_ = need;
            }
            cur_ -= need;
            cur = cheap;
        }
        else{
            int next = -1;
            double num = 1e9;
            for(int i = cur + 1 ; i <= N + 1 && sta[i].dist - sta[cur].dist <= res + eps ; ++i){
                if(sta[i].price < num - eps){
                    num = sta[i].price;
                    next = i;
                }
                else if(fabs(sta[i].price - num) <= eps && sta[i].dist > sta[next].dist){
                    next = i;
                }
            }
            tot += (c - cur_) * sta[cur].price;
            cur_ = c;
            double need = (sta[next].dist - sta[cur].dist) / l;
            cur_ -= need;
            cur = next;
        }
    }
    printf("%.2f\n" , tot);
    return 0;
}