• 11 Mortal Fibonacci Rabbits


    Problem

    Figure 4. A figure illustrating the propagation of Fibonacci's rabbits if they die after three months.

    Recall the definition of the Fibonacci numbers from “Rabbits and Recurrence Relations”, which followed the recurrence relation Fn=Fn1+Fn2Fn=Fn−1+Fn−2 and assumed that each pair of rabbits reaches maturity in one month and produces a single pair of offspring (one male, one female) each subsequent month.

    Our aim is to somehow modify this recurrence relation to achieve a dynamic programming solution in the case that all rabbits die out after a fixed number of months. See Figure 4 for a depiction of a rabbit tree in which rabbits live for three months (meaning that they reproduce only twice before dying).

    Given: Positive integers n100n≤100 and m20m≤20.

    Return: The total number of pairs of rabbits that will remain after the nn-th month if all rabbits live for mm months.

    Sample Dataset

    6 3
    

    Sample Output

    4

    # coding=utf-8
    ### 11. Mortal Fibonacci Rabbits ###
    
    # 0   1   1   2   2   3   4   5   7   9   12
    
    
    # method1
    def fibonacciRabbits(n, m):
        F = [0, 1, 1]
        for i in range(3, n + 1):
            if i <= m:
                total = F[i - 1] + F[i - 2]
            elif i == m + 1:
                total = F[i - 1] + F[i - 2] - 1
            else:
                total = F[i - 1] + F[i - 2] - F[i - m - 1]
            F.append(total)
        return (F[n])
    
    # print fibonacciRabbits(6,3)
    
    
    # method2
    def f(n, k):
        s = [0] * (k + 1)  # list *4 [0, 0, 0, 0]   s[0]代表当月出生的兔子,s[k]代表当月死亡的兔子
        s[0] = 1           # [1, 0, 0, 0]
        for x in range(1, n):
            s[1:k + 1] = s[0:k]
            print s
            s[0] = sum(s[2:])
        return sum(s[:-1])
    
    
    print f(10, 3)
    

      

  • 相关阅读:
    HDU 1114 Piggy-Bank
    HDU 2955 Robberies
    NTOJ 290 动物统计(加强版)
    POJ 3624 Charm Bracelet
    HDU 2602 Bone Collector
    POJ 1523 SPF(无向图割顶)
    HDU 5311 Hidden String
    HDU 1421 搬寝室
    HDU 1058 Humble Numbers
    POJ 3259 Wormholes(spfa判负环)
  • 原文地址:https://www.cnblogs.com/think-and-do/p/7274013.html
Copyright © 2020-2023  润新知