Problem Description
有一只经过训练的蜜蜂只能爬向右侧相邻的蜂房,不能反向爬行。请编程计算蜜蜂从蜂房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
这是一道递推的题,观察给出的图形,只有上下两行,容易想到1→2,3→4相当于一样的走法,这就涉及减法相同的问题了。那就只考虑从1到别的蜂房,1→2 1→3 1→4 1→5分别输出1 2 3 5,这就是斐波那契数列了,直接上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include <stdio.h> int main(void){ int t; long long f[55]; f[1]=1; f[2]=2; for(int i=3;i<55;i++){ f[i]=f[i-1]+f[i-2]; } scanf("%d",t); while(t--){ int n,m; scanf("%d%d",&n,&m); printf("%lld\n",f[m-n]); } return 0; }
|
或者使用斐波那契数列的通项公式来求,不过要注意公式中n的取值,因为数列:1 1 2 3 5 ……,我们不需要第一项。

1 2 3 4 5 6 7 8 9 10 11
| #include <stdio.h> #include <math.h> int main(void){ int n,a,b; scanf("%d",&n); while(n--){ scanf("%d%d",&a,&b); printf("%.0f\n",1.0*(pow((1+sqrt(5))/2.0,b-a+1)-pow((1-sqrt(5))/2.0,b-a+1))/sqrt(5)); } return 0; }
|