HDU 2044——一只小蜜蜂...【递推】

添加链接描述


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,终点为b-a+1
  • 无论终点在哪里,只能由前两个编号的位置传来
  • 所以递推式为:dp[i] = d[i-1] + dp[i+1]
  • 记忆化搜索

AC-Code

#include <bits/stdc++.h>
#define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
typedef long long ll;

ll dp[55];
ll f(ll x) {
    if (x <= 1)
        return x;
    else {
        if (dp[x] == 0)
            return dp[x] = f(x - 1) + f(x - 2);
        return dp[x];
    }

}
ll ans[55];
int main() {
    ios;
    for (int i = 1; i <= 50; i++) {
        ans[i] = f(i);
    }
    ll T;
    while (cin >> T) {
        while (T--) {
            ll a, b;
            cin >> a >> b;
            ll x = b - a + 1;
            cout << ans[x] << endl;
        }
    }
    return 0;
}
发布了104 篇原创文章 · 获赞 60 · 访问量 5863

猜你喜欢

转载自blog.csdn.net/Q_1849805767/article/details/103285697
今日推荐