苹果和虫子

GitHub跳转原题关系图返回列表

虫子啃过的苹果数是 ⌈y/x⌉(正在啃的那个也不完整),用 (y + x - 1) / x 向上取整一次算出,答案 max(n - ⌈y/x⌉, 0)。

OJ: roj

题目 ID: 1038

难度:入门

标签:入门数学python

创建: 2026-09-29 15:24

更新: 2026-10-04 23:06

题目描述

一箱 nn 个苹果混进一条虫子,它每 xx 小时吃掉一个,吃完一个才啃下一个;经过 yy 小时后还剩几个完整的苹果(被啃过一口的都不算完整)? 输入一行三个整数 n,x,yn, x, y,输出剩余个数。样例:输入 10 4 9,输出 7。

思路

虫子啃过的苹果数为 ⌈y/x⌉\lceil y/x \rceil:9 小时里啃完 2 个、正在啃第 3 个,这 3 个都不完整。用 (y + x - 1) / x 一次求出向上取整,答案取 max⁡(n−⌈y/x⌉, 0)\max(n - \lceil y/x \rceil,\ 0)(吃穿整箱时归零)。

参考代码

Python 版:

python
#!/usr/bin/env python3
# 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-09-29 15:25
# update_at: 2026-09-29 15:25

import sys


def eaten_apples(x: int, y: int) -> int:
    """x 小时啃完一个时 y 小时啃过的苹果数 ⌈y/x⌉:啃了一半的也不再完整。"""
    return -(-y // x)  # 整数向上取整


def solve() -> None:
    n, x, y = map(int, sys.stdin.buffer.read().split())
    remain = max(n - eaten_apples(x, y), 0)  # 吃到超出总数时按 0 算
    print(remain)


if __name__ == "__main__":
    solve()

C++ 版(同一算法):

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-10-04 23:06
 * update_at: 2026-10-04 23:06
 */

#include <cstdio>
#include <algorithm>

typedef long long ll;

int main() {
    ll n, x, y;
    scanf("%lld %lld %lld", &n, &x, &y);

    ll eaten = (y + x - 1) / x; // 向上取整:正在啃的这一个也算不完整
    ll remain = std::max(n - eaten, 0LL); // 虫子吃得比整箱还多时剩余按 0 算

    printf("%lld\n", remain);
    return 0;
}