渔夫分鱼- 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份,扔一条),以此为递归的结束,同时它也是验证鱼总数的开始。



posted @ 2011-09-30 22:41  haiyang.pan  阅读(648)  评论(0编辑  收藏  举报