洛谷 1016 旅行家的预算

A掉此题后我翻了几篇洛谷上的题解,发现大家的题解思路都比较高级,代码普遍特长,于是来写篇题解。

做法:贪心+模拟

大家似乎都是这个思路啊,没错,但我的思路应该算是最为简单的之一。

首先以油价位第一关键字,位置先后为第二关键字排序,然后从头到尾扫一遍,能加多少油就加多少油。

注意可以将起点终点当作中间站加入进去,以降低代码量。

AC代码:

#include <algorithm>
#include <cstdio>

double D, c, dis, cd, pri, d[12], p[12], go[12], ans = 0;
int n;

struct node
{
    double d, p;
    int num;
    bool operator < (const node & b) const
    { if (p == b.p) return num < b.num; return p < b.p; }
}sta[12];

signed main()
{
    scanf("%lf%lf%lf%lf%d", &D, &c, &dis, &pri, &n);
    for (int i = 1; i <= n; ++i)
    {
        scanf("%lf%lf", &d[i], &sta[i].p);
        p[i] = sta[i].p;
        sta[i].num = i;
    }
    sta[n + 1].p = 99999, sta[n + 1].num = n + 1, d[n + 1] = D, p[n + 1] = 99999;
    sta[n + 2].p = pri, sta[n + 2].num = 0, d[0] = 0, p[0] = pri;
    std::sort(sta + 1, sta + n + 3);
    for (int i = 1; i <= n + 1; ++i)
    {
        int u = sta[i].num;
        double res = c - (go[u] / dis);
        for (int j = u + 1; j <= n + 1; ++j)
        {
            if (res <= 0) break;
            if (go[j - 1] == d[j] - d[j - 1]) continue;
            cd = (d[j] - d[j - 1] - go[j - 1]) / dis;
            if (res >= cd) res -= cd, go[j - 1] = d[j] - d[j - 1], ans += p[u] * cd;
            else go[j - 1] = res * dis, ans += p[u] * res, res = 0;
        }
    }
    for (int i = 0; i <= n; ++i)
        if (go[i] != d[i + 1] - d[i])
        {
            puts("No Solution");
            return 0;
        }
    printf("%.2lf", ans);
    return 0;
}

 

posted @ 2018-10-30 00:07  Christopher_Yan  阅读(250)  评论(0编辑  收藏  举报