HOJ-2044:一只小蜜蜂...

一只小蜜蜂...

Problem Description
有一只经过训练的蜜蜂只能爬向右侧相邻的蜂房,不能反向爬行。请编程计算蜜蜂从蜂房a爬到蜂房b的可能路线数。
其中,蜂房的结构如下所示。

 

Input
输入数据的第一行是一个整数N,表示测试实例的个数,然后是N 行数据,每行包含两个整数a和b(0<a<b<50)。
 

Output
对于每个测试实例,请输出蜜蜂从蜂房a爬到蜂房b的可能路线数,每个实例的输出占一行。
 

Sample Input
 
  
21 23 6
 

Sample Output
 
  
13


分析:

1->3的路径:

        1->2->3 ;       1->3;

1->4的路径:

        1->2->4;        1->2->3->4;        1->3->4;        


  

    1->2       F(1->2)                                1条

    1->3       F(1->3)+F(1->2->3)            2条

    1->4        F(3->4) +F(2->4)  

                   =>F(1->3)+F(1->2)                    

                    =>2+1                                 

    1->5     F(4->5)+F(3->5)

                =>F(1->4)+F(1->3)           

                =>3+2

                 

所以n->m的路径,递归的思想的话:

        f(n, m-1)+f(n, m-2)     ,n!=m

        2                                ,n+2=m 

         1                                  , n+1=m


OJ运算会报错(Judge Status : Time Limit Exceeded)  ,递归会超时

既然题目已经给出数的范围,干脆根据范围把结果算完,放到数组,毕竟这比递归省时。

#include<iostream>
using namespace std;
int MAX=51;

__int64 f[51];


int main()
{
f[1]=1,f[2]=2;
int num,a,b;
for(int i=3;i<MAX;i++)
{
f[i]=f[i-1]+f[i-2];
}
while(cin>>num)
{
for(int i=0;i<num;i++)
{
cin>>a>>b;
if(a<b)
cout<<f[b-a]<<endl;
}
}
return 0; 



猜你喜欢

转载自blog.csdn.net/beautifulxu/article/details/80577016