P1016 旅行家的预算 解题报告

· · 题解

题目链接:https://www.luogu.com.cn/problem/P1016

【题目描述】

一个旅行家想驾驶汽车以最少的费用从一个城市到另一个城市(假设出发时油箱是空的)。给定两个城市之间的距离D1、汽车油箱的容量C(以升为单位)、每升汽油能行驶的距离D2、出发点每升汽油价格P和沿途油站数N(N可以为零),油站ii离出发点的距离Di、每升汽油价格Pi(i=1,2,…,N)。计算结果四舍五入至小数点后两位。如果无法到达目的地,则输出“No Solution”。

【输入格式】

第一行,D1,C,D2,P,N。

接下来有N行。

第i+1行,两个数字,油站i离出发点的距离Di和每升汽油价格Pi。

【输出格式】

所需最小费用,计算结果四舍五入至小数点后两位。如果无法到达目的地,则输出“No Solution”。

【解题思路】

借助(https://www.luogu.com.cn/discuss/show/134434)的思想

本题考虑贪心+dfs

具体看注释

【AC代码】

#include <bits/stdc++.h>
using namespace std;
struct node
{
    double d, t;  //d代表距离,t代表邮费
    bool operator < (const node& b)const
    {
        if (d == b.d) return t < b.t;
        return d < b.d;
    }
}a[10];  //记录站点信息
int n;
double ans, d1, c, d2, p;
inline void dfs(int pos, double tot, double rest)  //pos指当前所在站点编号,tot指目前花费,rest代表剩余油量
{
    if (pos == n + 1)  //结束条件为到达终点
    {
        ans = min(ans, tot);  //更新答案
        return;
    }
    for (int i = pos + 1; i <= n + 1; ++i)  //从当前站点往后搜
    {
        if (a[i].d - a[pos].d <= c * d2)  //如果i站点加满油也到不了直接return
        {
            if (a[i].t > a[pos].t) dfs(i, tot + (c - rest) * a[pos].t, c - (a[i].d - a[pos].d) / d2); 
            //如果下一个站点油贵,在当前站点把油加满
            else  //如果下一个站点邮费便宜,考虑在当前站点尽量少买油(贪心)
            {
                if (rest * d2 >= a[i].d - a[pos].d) dfs(i, tot, rest - (a[i].d - a[pos].d) / d2);  //如果剩余油量能到下一站点,不加油
                else dfs(i, tot + ((a[i].d - a[pos].d - rest * d2) / d2) * a[pos].t, 0.0); //否则将油加至刚好能到
            }
        }
        else return;
    }
}
int main()
{
    scanf("%lf%lf%lf%lf%d", &d1, &c, &d2, &p, &n);
    double temp = c * d2;
    for (int i = 1; i <= n; i++)
    {
        scanf("%lf%lf", &a[i].d, &a[i].t);
        if (a[i].d - a[i - 1].d > temp) { puts("No Solution"); return 0; }  //如果两个站点间的距离我加满油也到不了,直接return
    }
    sort(a + 1, a + n + 1);  //按照距离排序
    a[0].d = 0.0;  //设置起点
    a[0].t = p;
    a[n + 1].d = d1;  //设置终点
    a[n + 1].t = 0.0;
    ans = 0x3f3f3f3f / 1.0; //将答案初始化为无穷
    dfs(0, 0.0, 0.0);  //开始爆搜
    printf("%.2f\n", ans);
    return 0;
}