hdu2044 一只小蜜蜂(递推)

题目链接https://vjudge.net/contest/205698#problem/K

题目如下

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

Input

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

Output

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

Sample Input

2
1 2
3 6

Sample Output

1
3

假设小蜜蜂从第一个蜂房开始爬,到第i个蜂房,路径有f(i)种,可知

f(1)=0; f(2)=1; f(3)=2;

而要到达第i个蜂房有两种路径:1、从i-1过去,有f(i-1)种路径

                                                    2、从i-2过去,有f(i-2)种路径

那么f(i)=f(i-1)+f(i-2)

题目中是从第a个蜂房到第b个蜂房,那么把第a个蜂房看做第一个蜂房,第b个蜂房就应该是第b-a+1个蜂房,有f(b-1+1)种方法

为了防止超时,用打表的方法

代码如下

#include <iostream>
#include<cstdio>
using namespace std;
typedef long long ll;
ll a[1000];
void creat()
{
	a[1]=0;
	a[2]=1;
	a[3]=2;
	for(int i=4;i<50;i++)
		a[i]=a[i-1]+a[i-2];
}
int main()
{
	int n;
	scanf("%d",&n);
	while(n--)
	{
		int a1,b;
		scanf("%d%d",&a1,&b);
		creat();
		printf("%I64d\n",a[b-a1+1]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41626975/article/details/82012663
今日推荐