一只小蜜蜂

一只小蜜蜂

有一只经过训练的蜜蜂只能爬向右侧相邻的蜂房,不能反向爬行。请编程计算蜜蜂从蜂房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类型会导致取值范围不够

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

potao1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值