题解 P1086 【花生采摘】

· · 题解

这道题不需要记录整个图啊orz,题干上写了有些地方没有花生,所以能节省就节省一点呗。
我把路上视作x = 0,而花生田的坐标从1开始。记录每个花生丛的坐标和价值。那么从当前位置到收获下一个花生最小花费就是

那么就很容易做了,再使用优先队列,在输入花生时就可以得到采摘顺序,只需要在(队列非空)或者(下一个花生无法采摘)的情况跳出采摘循环即可。

下面是代码:


#include <bits/stdc++.h>//头文件
using namespace std;//命名空间

class Peanut//花生类
{
public:
    Peanut(){}
    Peanut(int x, int y, int value)//构造函数
    {
        this->x = x;
        this->y = y;
        this->value = value;
    }

    int x, y, value;//坐标和价值

    bool operator<(const Peanut &other) const
    {
        //重载小于号,按价值排序
        return this->value < other.value;
    }
};

//优先队列存储花生信息(STL大发吼啊)
priority_queue<Peanut> peanuts;

int main(int argc, char const *argv[])
{
    //平凡地输入
    int m, n, k; scanf("%d%d%d", &m, &n, &k);

    for (int i = 1; i <= m; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            //当当前位置有花生时,录入信息
            int tmp; scanf("%d", &tmp);
            if (tmp != 0)
            {
                peanuts.push(Peanut(i, j, tmp));
            }
        }
    }

    //初始化位置信息,稍微特判一下没有花生的情况
    //value_get是当前收获的花生数
    int x = 0, y = (!peanuts.empty())? peanuts.top().y: 0, value_get = 0;
    //当队列非空时
    while (!peanuts.empty())
    {
        //优先队列的第一位就是最有价值的花生植株
        Peanut max_now = peanuts.top();

        //计算最小花费
        int mincost = abs(max_now.x - x) + abs(max_now.y - y) + max_now.x + 1;
        //如果摘了这株花生就回不去了的话
        if (mincost > k)
        {
            //就不能再摘了,回去
            break;
        }
        else//如果还能摘
        {
            //耗消耗时间,获取花生,位置移动,花生消失
            k -= mincost - max_now.x;
            value_get += max_now.value;
            x = max_now.x;
            y = max_now.y;
            peanuts.pop();
        }
    }

    //采摘完成,输出
    printf("%d\n", value_get);

    return 0;
}

希望能给后来的人带来一点帮助orz