[NOIP 2005 普及组] 陶陶摘苹果

先算踩凳后的可达高度,再用生成器表达式统计不超过该高度的苹果数。

OJ: luogu

题目 ID: P1046

难度:入门

标签:python入门模拟枚举

日期: 2026-07-15 18:17

题意

给出 10 个苹果高度和陶陶伸手可达高度。陶陶有 30 厘米高的板凳,求她能摘到多少个苹果。

思路

陶陶最终可达高度是 taotao + 30。只要苹果高度 height <= reach,就能摘到。

这题已有旧 C++ 版本;本篇改成 Python 教学,重点是列表输入和用 sum 统计满足条件的个数。brute.py 不单独写,因为逐个统计就是完整解法。

Python 知识

  • list(map(int, input().split())) 读取一行整数列表。
  • sum(1 for height in heights if height <= reach) 会对每个可摘到的苹果贡献 1
  • 生成器表达式适合“统计满足条件的数量”这类短逻辑。

对应的本地 Python 笔记:

  • /home/rainboy/mycode/hugo-blog/content/program_language/python/input_output_and_strings.md:列表输入和输出。
  • /home/rainboy/mycode/hugo-blog/content/program_language/python/generator_expression.md:生成器表达式与 sum
  • /home/rainboy/mycode/hugo-blog/content/program_language/python/oj_input_output_cheatsheet.md:多行输入格式。

代码

python
heights = list(map(int, input().split()))
taotao = int(input())

reach = taotao + 30
answer = sum(1 for height in heights if height <= reach)

print(answer, end="")

Guide 风格代码

cppbook《C++ 快速入门》教学风格的写法(std:: 前缀、i += 1 循环、0 起始下标):

cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-08-14 15:18
 * update_at: 2026-08-14 15:18
 */
/* P1046 陶陶摘苹果:读入 10 个苹果高度,统计踩上板凳后能够到的苹果数。 */

#include <iostream>

int main() {
    const int apple_count = 10;
    int height[apple_count];  // 10 个苹果离地的高度

    for (int i = 0; i < apple_count; i += 1) {
        std::cin >> height[i];
    }

    int hand_reach;
    std::cin >> hand_reach;

    // 踩上 30 厘米的板凳后,能够到的最大高度
    int reachable = hand_reach + 30;

    // 高度不超过 reachable 的苹果都能摘到
    int answer = 0;
    for (int i = 0; i < apple_count; i += 1) {
        if (height[i] <= reachable) {
            answer += 1;
        }
    }

    std::cout << answer << '\n';
    return 0;
}

Pythonic 写法

sum 布尔计数:

python
heights = list(map(int, input().split()))
reach = int(input()) + 30
print(sum(h <= reach for h in heights))

复杂度

固定检查 10 个苹果,时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

总结

这类题先算阈值,再统计不超过阈值的元素个数。Python 中 sum(1 for ... if ...) 很适合表达计数。