(递推)一只小蜜蜂... hdu2044

一只小蜜蜂...

链接:http://acm.hdu.edu.cn/showproblem.php?pid=2044

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 95054    Accepted Submission(s): 33882


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
 
就是汉诺塔问题的翻版
 
Java代码:
import java.math.BigInteger;
import java.util.Scanner;

public class Main {
    public static BigInteger func(int num) {
        BigInteger[] bigIntegers = new BigInteger[51];
        bigIntegers[1] = BigInteger.valueOf(1);
        bigIntegers[2] = BigInteger.valueOf(2);
        for(int i = 3;i <=num;i++) {
            bigIntegers[i] = bigIntegers[i-1].add(bigIntegers[i-2]);
        }
        return bigIntegers[num];
    }

    public static void main(String[] args) {
        @SuppressWarnings("resource")
        Scanner inScanner = new Scanner(System.in);
        int number = inScanner.nextInt();
        while(number-->0) {
            int a = inScanner.nextInt();
            int b = inScanner.nextInt();
            System.out.println(func(b-a));
        }
    }

}

C++代码:

#include <iostream>
using namespace std;
long long fun(int n)
{
    long long a[51];                 
    a[1]=1;
    a[2]=2;
    for(int i=3;i<=n;i++)             //可以用这个递推方法,减少计算量。注意运用数组。
        a[i]=a[i-1]+a[i-2];
    return a[n];
}
int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        int a,b;
        cin>>a>>b;
        printf("%lld\n",fun(b-a));
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Weixu-Liu/p/9651562.html
今日推荐