李白喝酒问题

一、问题提出。

“李白街上走,提壶去买酒,遇店加一倍,见花喝一斗”,
途中,遇见5次店,见了10此花,壶中原有2斗酒,最后刚好喝
完酒,要求最后遇见的是花,求可能的情况有多少种?

二、设计思路。

分析:题目要求最后是遇见花也就是说最后是喝酒(最好刚好把酒完),出去这种确定的情况,最后剩下的情况是:还有一斗酒,前面遇到了5次店和九次花(打了5次酒,喝了九次酒)。
然后每次情况只有两种分别是遇见花喝酒和遇到店打酒。
遇到店的时候打酒(s*2),然后酒的斗数会翻倍;遇到花时喝酒,然后酒的斗数减一(s-1);
然后设置递归的出口:
当酒喝完还遇见花时,则return 0;以为酒不能是负的;
当5个店已经都遇见过时,则return 0;
当9个花已经都遇见过时,则return 0;
当花刚好遇见完,店刚好遇见完,酒还有一斗时:return 1;
当中间过程,酒喝完了,但是遇见店了,又因为此时s=0,遇到店的时候打酒(s*2),所以要把s设置成0.5;

 

代码实现。

#include <stdio.h>
int count = 0;
void fun(int store, int flower, int alco)
{
    if (5 < store || 10 < flower)       
    {
        return ;
    }
    if (5 == store && 9 == flower)
    {
        if (1 == alco)
        {
            count++;
        }
        return ;
    }
    fun(store + 1, flower, alco * 2);
    fun(store, flower + 1, alco - 1);   
}

int main()
{
    fun(0, 0, 2);           //初始情况:酒为2,其余为0

    printf ("共有 %d 种可能\n", count);

    return 0;
}

 

posted @ 2023-04-25 22:36  liuxuechao  阅读(141)  评论(0编辑  收藏  举报