一只小蜜蜂
有一只经过训练的蜜蜂只能爬向右侧相邻的蜂房,不能反向爬行。请编程计算蜜蜂从蜂房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
求解
/*使用递归求解会产生超时问题*/
//测试数据多使用边界数据进行测试
#include <stdio.h>
#include <time.h>
long long int route(int n)
{
if (n == 1) {
return 1;
}
if (n == 2) {
return 2;
}
return route(n - 1) + route(n - 2);
}
int main()
{
clock_t start, finish;
double total_time;
start = clock();
int n, a, b;
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%d %d", &a, &b);
printf("%lld\n", route(b - a));
}
/*这里测试代码运行时间*/
finish = clock();
total_time = (double) (finish - start) / CLOCKS_PER_SEC;
printf("%lf seconds/n\n",total_time);
}
/*使用数组不会超时*/
# include <stdio.h>
int main(void)
{
int n, a, b;
long long int h[50];
scanf("%d", &n);
while (n--) {
scanf("%d %d", &a, &b);
h[0]=0;
h[1]=1;
h[2]=2;
for(int i = 3; i <= b; i++) {
h[i] = h[i-1] + h[i-2];
}
printf("%lld\n", h[b-a]);
}
}
🔔数组定义使用long long
类型,输入数据可以使用1 49
来测试,int
类型会导致取值范围不够
本文含有隐藏内容,请 开通VIP 后查看