洛谷题单指南-贪心-P1478 陶陶摘苹果(升级版)

原题链接:https://www.luogu.com.cn/problem/P1478

题意解读:题目的本质是任务安排问题,有n件任务,每件任务耗时不同,在一定的时间内,如何安排任务使得完成的任务越多越好。

解题思路:

对于这类问题,贪心策略是优先完成容易的。

回到摘苹果问题,要优先摘耗费力气小的,

如果高度够不着,就跳过,其他没有什么难点。

100分代码:

#include <bits/stdc++.h>
using namespace std;

const int N = 5005;

struct apple
{
    int x, y; //x:苹果高度 y:摘苹果力气
} ap[N];

bool cmp(apple a1, apple a2)
{
    return a1.y < a2.y; //按摘苹果所需力气由小到大排序,策略是先摘轻松的
}

int n, s, a, b, ans;

int main()
{
    cin >> n >> s >> a >> b;
    for(int i = 1; i <= n; i++) cin >> ap[i].x >> ap[i].y;

    sort(ap + 1, ap + n + 1, cmp); 

    for(int i = 1; i <= n; i++)
    {
        if(a + b < ap[i].x) continue; //高度够不着
        if(s >= ap[i].y) ans++, s -= ap[i].y;
    }

    cout << ans;

    return 0;
}

 

posted @ 2024-02-23 13:02  hackerchef  阅读(149)  评论(0)    收藏  举报