• HDU2018 斐波那契


    题解:

    斐波那契数列的变形,递归求解即可。

    设第n年有cow(n)头母牛

    根据题意,第一年有1头,第二年有2头,第三年有3头。

    当n>3,在cow(n)头母牛中,有cow(n-2)头可以生小母牛,所以下一年的母牛数cow(n+1) = cow(n) + cow(n-2)

    所以求第n年母牛数的递推公式为:cow(n) = cow(n-1) + cow(n-3)

    代码:

     1 #include <iostream>
     2 using namespace std;
     3 int cow(int n)
     4 {
     5     if(1 > n)    return 0;
     6     if(1 == n)
     7         return 1;
     8     if(2 == n)    
     9         return 2;
    10     if(3 == n)    
    11         return 3;
    12     else
    13         return cow(n-1) + cow(n-3);        
    14 } 
    15 int main(int argc, char *argv[])
    16 {
    17     int n;
    18     while(1)
    19     {
    20         cin>>n;
    21         if(0 == n)
    22             return 0;
    23         cout<<cow(n)<<endl; 
    24     } 
    25     return 0;
    26 }
  • 相关阅读:
    poj 3669 Meteor Shower
    poj 3232 Accelerator
    poj 2155 Matrix
    poj 3628 Bookshelf 2
    cf C. Maze
    cf B. Fox Dividing Cheese
    hdu Children’s Queue
    cf D. Broken Monitor
    cf C. Mittens
    cf B. Berland Bingo
  • 原文地址:https://www.cnblogs.com/mycd/p/5658075.html
Copyright © 2020-2023  润新知