渔夫分鱼- C实现

中午吃饭的时候老婆用MSN发过来如下题目,中午也没太在意,晚上回家后,写个代码实现了一下:

题目:A,B,C,D,E五个渔夫夜间合伙捕鱼,,第二天清A先醒来,他把鱼均分五份,把多余的一条扔回湖中,便拿了自己的一份回家了,B醒来后,也把鱼均分五份,把多余的一条扔回湖中,便拿了自己的一份回家了,C,D,E也按同样方法分鱼。问5人至少捕到多少条鱼

#include <stdio.h>
#include <sys/time.h>

int get_total_fish2 ()
{
    int i = 0, j = 0;
    int total = 0;

    for (j = 1; j < 10000; ++j)
    {
        total = j;
        for (i = 0; i < 5; ++i)
        {
            if (total < 1)
                break;
            total -= 1;

            if (total % 5 != 0)
                break;
            total /= 5;
            total *= 4;

            if (i == 4)
            {
                return j;
            }
        }
    }
    return 0;
}

int get_total_fish1 (int person)
{
    int total = 0;

    if (person == 1)
    {
        // the last fishman at least get one fish
        static int num = 1;
        total = num * 5 + 1;
        ++num;
        return total;
    }
    else
    {
        while (1)
        {
            total = get_total_fish1 (person - 1);
            if (total % 4 != 0 || total <= 0)
                continue;
            else
            {
                total /= 4;
                total *= 5;
                total += 1;
                return total;
            }
        }
    }
}

int main ()
{
    int num = 0;
    int time = 0;
    struct timeval time_start, time_end;

    gettimeofday (&time_start, NULL);
    num = get_total_fish1 (5);
    gettimeofday (&time_end, NULL);
    time = (time_end.tv_sec - time_start.tv_sec) * 1000000 + (time_end.tv_usec - time_start.tv_usec);
    printf ("total num of fish is %d, cost time %d usec\n", num, time);

    gettimeofday (&time_start, NULL);
    num = get_total_fish2 ();
    gettimeofday (&time_end, NULL);
    time = (time_end.tv_sec - time_start.tv_sec) * 1000000 + (time_end.tv_usec - time_start.tv_usec);
    printf ("total num of fish is %d, cost time %d usec\n", num, time);
    return 0;
}

get_total_fish2()

这个方法的思路比较简单也容易想到,与方法1比较在性能上有些不足 - 可以从运行结果的输出中看出。

具体思路:从1开始,尝试每个数字是否符合条件,直到找到第一个正确的数。

get_total_fish1()

利用递归调用来实现,从最后一个渔夫开始,根据规则,最后一个渔夫最少要拿到一条鱼(共6条,分5份,扔一条),以此为递归的结束,同时它也是验证鱼总数的开始。



转载于:https://www.cnblogs.com/haiyang/archive/2011/09/30/2196875.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值