天天看点

信息学奥赛一本通 1038:苹果和虫子 | OpenJudge NOI 1.3 15 | OpenJudge NOI 1.4 21

【题目链接】

ybt 1038:苹果和虫子

OpenJudge NOI 1.3 15:苹果和虫子

OpenJudge NOI 1.4 21:苹果和虫子2

【题目考点】

1. if…else语句

if(判表达式)

{语句段1}

else

{语句段2}

如果判断表达式的值为true,运行语句段1。如果判断表达式的值为false,运行语句段2。

2. 比较函数max, min(存在于< algorithm >头文件中)

  • int max(int a, int b);

    double max(double a, double b);

    返回a,b中较大的值
  • int min(int a, int b);

    double min(double a, double b);

    返回a,b中较小的值

【解题思路】

解法1:列数学公式

  • 虫子每x小时能吃掉1个苹果,所以1小时能吃掉 1 x \frac{1}{x} x1​个苹果,y小时能吃掉 y x \frac{y}{x} xy​个苹果。
  • 已知共有n个苹果,y小时后还剩下 n − y x n-\frac{y}{x} n−xy​个苹果,剩下的苹果中可能存在不完整的苹果(即 n − y x n-\frac{y}{x} n−xy​可能是小数),完整的苹果个数为 ⌊ n − y x ⌋ \lfloor n-\frac{y}{x}\rfloor ⌊n−xy​⌋(向下取整)。
  • 但苹果个数最少为0,所以最终剩下的完整的苹果个数为 m a x ( 0 , ⌊ n − y x ⌋ ) max(0, \lfloor{n-\frac{y}{x}}\rfloor) max(0,⌊n−xy​⌋)

解法2:判断不同情况

  1. 先判断虫子y小时毁掉的苹果数量(包括被完全吃掉及吃一半的苹果),如果y是x的整数倍,那么虫子y小时吃掉了 y x \frac{y}{x} xy​个完整的苹果,如果y不是x的整数倍,虫子还额外毁掉了1个苹果(吃一半),共毁掉 y x + 1 \frac{y}{x}+1 xy​+1个苹果。
  2. 计算剩下的完整的苹果数量,为总苹果数n减去毁掉的苹果数。
  3. 如果计算出来剩下的苹果比0少,那么就是剩下0个苹果。

【题解代码】

解法1:列数学公式

#include <bits/stdc++.h>
using namespace std;
int main()
{
	double n, x, y;
	cin>>n>>x>>y;
	cout<<max(0, (int)floor(n - y / x));//调用int max(int a, int b);求两个数的最大值 
	return 0;
}
           

解法2:判断不同情况

用if…else语句

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n, x, y, rest;
    cin>>n>>x>>y;
    if (y%x == 0)
        rest = n - y/x;
    else
        rest = n - y/x - 1;
    if (rest <= 0)
        cout<<0<<endl;
    else
        cout<<rest<<endl;
	return 0;
}
           

解法3:判断不同情况

用三目运算符 ? :

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n, x, y, res;
    cin>>n>>x>>y;
   	res = n - y/x - (y%x == 0 ? 0 : 1);
   	cout << (res <= 0 ? 0 : res);
    return 0;
}
           

继续阅读