a_lc_完成所有任务的最少初始能量(反向思维+贪心)

有一个任务i,它的要求是([x_i, y_i]),xi表示花费的实际能量,yi表示完成该任务前你需要拥有的能量,问完成所有任务需要的最少能量

思路:这题一直wa没做出来,思路是:

  • 因为我们最终要把任务全都做完,所以优先做 (y_i-x_i) 差值大的任务,因为做完这样的任务后,可以收获的能量较多
class Solution {
public:
    struct node {
        int cost, thre;
        bool operator<(const node& b) const { return thre-cost<b.thre-b.cost; }
    };
    int minimumEffort(vector<vector<int>>& tasks) {
        int ans=0, remain=0;
        priority_queue<node, vector<node>> q;
        for (auto& task : tasks) q.push({task[0], task[1]});

        while (!q.empty()) {
            node task=q.top(); q.pop();
            if (remain>=task.thre) { //能用之前省下来的能量解决
                remain-=task.cost;
            } else {
                ans+=task.thre-remain; //否则,则需要花费task.thre-remain的能量
                remain=task.thre-task.cost;
            }
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/wdt1/p/14019791.html