zoukankan      html  css  js  c++  java
  • 百钱买百鸡的问题(递归解法)

    题目:公鸡5文钱一只,母鸡3文钱一只,小鸡3只一文钱,

    用100文钱买一百只鸡,其中公鸡,母鸡,小鸡都必须要有,问公鸡,母鸡,小鸡要买多少只刚好凑足100文钱。

    为程序计算方便,转换一下数字,公鸡15钱一只,母鸡9钱一只,小鸡1钱一只.用三百文钱买一百只鸡,其中公鸡,母鸡,小鸡都必须要有,问公鸡,母鸡,小鸡要买多少只刚好凑足300文钱。

    常规解法:

     1 class Program
     2     {
     3         static void Main(string[] args)
     4         {
     5             //公鸡的上线
     6             for (int x = 1; x < 20; x++)
     7             {
     8                 //母鸡的上线
     9                 for (int y = 1; y < 33; y++)
    10                 {
    11                     //剩余小鸡
    12                     var z = 100 - x - y;
    13 
    14                     if ((z % 3 == 0) && (x * 5 + y * 3 + z / 3 == 100))
    15                     {
    16                         Console.WriteLine("公鸡:{0}只,母鸡:{1}只,小鸡:{2}只", x, y, z);
    17                     }
    18                 }
    19             }
    20             Console.Read();
    21         }
    22     }

    递归解法:

     1 #include <iostream>
     2 #include <iomanip>
     3 #include <algorithm>
     4 using namespace std;
     5 const int CHICK_KIND = 3;
     6 const int TOTAL_MONEY=300;
     7 const int TOTAL_COUNT=100;
     8 
     9 int priceArray[CHICK_KIND]={15,9,1};
    10 int resultArray[CHICK_KIND]={0,0,0};
    11 
    12 void calculate(int remain_money,int index);
    13 int main(int argc,char **argv)
    14 {
    15     calculate(TOTAL_MONEY,0);
    16 
    17     return 0;
    18 }
    19 void calculate(int remain_money,int index)
    20 {
    21     int time=remain_money/priceArray[index];
    22 
    23     for(int i=0;i<=time;i++)
    24     {
    25         resultArray[index]=i;
    26         if(index==CHICK_KIND-1)
    27         {
    28             if(resultArray[0]+resultArray[1]+resultArray[2]==TOTAL_COUNT&&resultArray[0]>0&&resultArray[1]>0&&resultArray[2]>0)
    29                 if(resultArray[0]*priceArray[0]+resultArray[1]*priceArray[1]+resultArray[2]*priceArray[2]==TOTAL_MONEY)
    30                     cout<<"("<<resultArray[0]<<","<<resultArray[1]<<","<<resultArray[2]<<")"<<endl;
    31         }
    32         else
    33         {
    34             int remainMoney=remain_money;
    35             remainMoney=remainMoney-priceArray[index]*resultArray[index];
    36             calculate(remainMoney,index+1);
    37         }
    38     }
    39 }
    生活的残酷,让我们习惯了忘记疲倦,一直奔向远方,追寻着自己的梦想。
  • 相关阅读:
    ABAP术语-Interface
    ABAP术语-Interface Parameter
    ABAP术语-Implementation
    ABAP术语-IDOC
    ABAP术语-IAC (Internet Application Components)
    ABAP术语-HTML
    ABAP术语-Function Module
    ABAP术语-Function Library
    ABAP术语-Function Group
    PyCharm的小技巧
  • 原文地址:https://www.cnblogs.com/L-Arikes/p/5092033.html
Copyright © 2011-2022 走看看