新手村 Boss战-入门综合练习1 陶陶摘苹果(升级版)

题目链接

题意理解

这题就是说,你要能按照摘苹果需要力气的大小排序,需要小的在前面,这样才能贪一波。

代码

#include <cstring>
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>

using namespace std;

typedef struct {
    int x; // height
    int y; // strength
} Apple;


const int maxn = 5050;
Apple apple[maxn];

int n, s;
int a, b;

void read(int &x) {
    x = 0;
    int f = 1;
    char ch = getchar();
    while(ch > '9'||ch < '0') {
        if(ch == '-') {
            f = -1;
        }
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9') {
        x = x * 10 + (int)(ch - 48);
        ch = getchar();
    }
    x = x * f;
}

int cmp(Apple a1, Apple a2) {
    return a1.y < a2.y;
}


int main() {
    read(n);
    read(s);
    read(a);
    read(b);
    for(int i = 0; i < n; i++) {
        read(apple[i].x);
        read(apple[i].y);
    }
    sort(apple, apple + n, cmp);
    int cnt = 0;
    for(int i = 0; i < n; i++) {
        if(s >= apple[i].y) {
            if(a + b >= apple[i].x) {
                s -= apple[i].y;
                cnt++;
            }
        } else {
            break;
        }
    }
    cout << cnt << endl;
    return 0;
}

欢迎加入“不会算法一群菜鸟”,群号是⑥⑥①⑨②2025,这是我设置的一道很低的门槛用来阻止广告的。入群的验证暗号是:我爱编译原理

### 关于P1478陶陶摘苹果升级版题目解析 #### 题目描述 给定n个苹果到达地面的高度`xi`,椅子的高度`a`,陶陶手伸直的最大长度`b`,以及陶陶剩余的力气`s`。对于每一个苹果,给出其距离地面的具体高度,并且提供摘取该苹果所需的特定力气值`yi`。目标是在陶陶的力气耗尽前(`s<0`)计算并返回能够成功摘得的苹果数量最大值。 #### 数据输入格式说明 程序接收一系列参数作为输入数据,具体包括但不限于: - 苹果总数`n` - 椅子增加后的总可达高度`(a+b)` - 剩余可用力气总量`s` - 接下来的一系列成对的数据代表各个苹果离地的实际高度及其对应的采摘所需耗费的力量[^2] #### 解决方案概述 为了使陶陶能够在有限的体力范围内获取尽可能多的果实,合理的策略是对所有待选对象按照其所需付出的努力程度从小到大排序;优先处理那些成本较低的任务可以有效提升整体效率。因此,在此情境下应当首先考虑按升序排列各苹果对应的需求力量列表,之后逐一尝试收集直到无法继续为止[^3]。 #### 实现细节分析 考虑到上述逻辑流程,下面是一个基于C++语言实现这一算法思路的例子: ```cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; struct Apple { int height; int effort; }; bool compare(Apple a, Apple b){ return a.effort < b.effort; } int main(){ int n,a,b,s,x,y; cin>>n>>a>>b>>s; vector<Apple> apples(n); for(int i=0;i<n;++i){ cin >> x >> y; if(x<=a+b){ // 只记录可触及范围内的苹果 apples[i].height=x; apples[i].effort=y; }else{ apples[i].effort=s+1; // 将不可达苹果标记为不可能被选择的状态 } } sort(apples.begin(),apples.end(),compare); int count = 0; for(auto &apple : apples){ if(s>=apple.effort && apple.effort!=s+1){ ++count; s-=apple.effort; } } cout<<count<<"\n"; } ``` 通过这段代码实现了对问题的有效解决方法,即先过滤掉超出能力范围的目标,接着依据消耗代价由低至高遍历筛选符合条件的对象直至资源不足以支撑进一步行动。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值