2750 鸡兔同笼

2750:鸡兔同笼

总时间限制: 
1000ms
内存限制: 
65536kB
描述

一个笼子里面关了鸡和兔子(鸡有2只脚,兔子有4只脚,没有例外)。已经知道了笼子里面脚的总数a,问笼子里面至少有多少只动物,至多有多少只动物。

输入
一行,一个正整数a (a < 32768)。
输出
一行,包含两个正整数,第一个是最少的动物数,第二个是最多的动物数,两个正整数用一个空格分开。
如果没有满足要求的答案,则输出两个0,中间用一个空格分开。
样例输入
20
样例输出
5 10














【思路】枚举法进行判断。注意先判断是否有解,没有的话输出两个0。

【代码】AC的C++代码如下:

#include <iostream>
using namespace std;

int main()
{
    int a;
    int min = 32768,max = 0;
    int total;  //鸡兔的总数
    cin >> a;
    if (a % 2 != 0)     //若脚的数量是奇数,无解
        cout << "0 0" << endl;
    else
    {
        for (int x = 0;x <= a / 2;x++)    //鸡的数量
        {
            for (int y = 0;y <= a / 4;y++)   //兔的数量
            {
                if (x * 2 + y * 4 == a)
                {
                    total = x + y;
                    if (total < min)
                        min = total;
                    if (total > max)
                        max = total;
                }
            }
        }
        cout << min << " " << max << endl;
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_38056893/article/details/80216531