苹果和虫子2

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

向上取整统计已被吃或正在被吃的苹果,并将剩余数下限限制为零。

OJ: noi_openjudge

题目 ID: ch0104-21

难度:入门

标签:数学条件判断python

日期: 2026-07-30 23:01

题意

xx 小时吃完一个苹果,经过 yy 小时求剩余完整苹果数;输入不保证剩余数非负。

思路

被吃或正在吃的苹果数是 y/x\lceil y/x\rceil,正整数向上除法为 (y + x - 1) // x。第 2 版还要用 max(0, ...) 防止答案小于零。

代码

Python代码

python
apples, hours_per_apple, hours = map(int, input().split())
eaten = (hours + hours_per_apple - 1) // hours_per_apple
print(max(0, apples - eaten))

C++代码

cpp
#include <cstdio> 
int main(){
    int n,x,y;
    scanf("%d%d%d",&n,&x,&y);
    int ans = y / x;
    if( y % x !=0)
        ans++;
    if( n - ans <0)
        printf("0");
    else
        printf("%d\n",n-ans);
    return 0;
}

复杂度

时间复杂度和额外空间复杂度均为 O(1)O(1)

总结

当题目允许耗时超过库存时,除了向上取整,还要显式处理结果下界。