题解:P1478 陶陶摘苹果(升级版)

· · 题解

大意

有 n 个苹果,每个苹果的高度为 x_i,摘下需要花费 y_i 的力气。陶陶有 s 点力气,他的手伸直的最大长度为 b,够不到可以踩着高度为 a 的凳子摘苹果。

请求出陶陶最多可以摘下的苹果数。

解析

已知陶陶手伸直的最大长度为 b,凳子的高度为 a,也就是说他最多可以摘到高度为 a + b 的苹果。所以,比这个高度还高的苹果对求解没有帮助,直接排除。

然后考虑贪心。我们可以把剩下的苹果按需要的力气值升序排序,从花费力气最小的开始摘,直到 s < 0。此时的答案就是最佳答案。

代码

#include <cstdio>
#include <algorithm>
using namespace std;
struct apple{
    int x, y;
} apples[5005];
bool cmp(apple a, apple b) {
    return a.y < b.y;
}
int main() {
    int n, a, b, s, ans = 0, m = 0; //ans为答案,m为筛选后的苹果个数
    apple tmp; //当前输入的苹果数据
    scanf ("%d %d\n%d %d", &n, &s, &a, &b);
    for (int i = 1; i <= n; i++) {
        scanf("%d %d", &tmp.x, &tmp.y);
        if (tmp.x <= (a + b)) //筛选高度小于a+b的苹果
            apples[++m] = tmp;
    }
    sort(apples + 1, apples + m + 1, cmp);
    for (int i = 1; i <= m; i++) {
        s -= apples[i].y;
        if (s < 0) //力气耗尽
            break;
        else
            ans++;
    }
    printf("%d", ans);
    return 0;
}

过了。