【洛谷 P2437】蜜蜂路线 题解(递归+记忆化搜索+高精度)

蜜蜂路线

题目描述

一只蜜蜂在下图所示的数字蜂房上爬动,已知它只能从标号小的蜂房爬到标号大的相邻蜂房,现在问你:蜜蜂从蜂房 m m m 开始爬到蜂房 n n n m < n m<n m<n,有多少种爬行路线?(备注:题面有误,右上角应为 n − 1 n-1 n1

输入格式

输入 m , n m,n m,n 的值

输出格式

爬行有多少种路线

样例 #1

样例输入 #1

1 14

样例输出 #1

377

提示

对于100%的数据, 1 ≤ M , N ≤ 1000 1 \le M,N\le 1000 1M,N1000

思路

f(x) = f(x - 1) + f(x - 2)
如果m == x或m + 1 == x,则f(x) = 1
数据过大,long long不够大,必须上高精度。

AC代码

#include <iostream>
#include <vector>
#define AUTHOR "HEX9CF"
using namespace std;

const int maxn = 1005;

int n, m;
vector<int> mem[maxn];

vector<int> add(vector<int> v1, vector<int> v2) {
	vector<int> v3;
	vector<int>::iterator it1 = v1.begin();
	vector<int>::iterator it2 = v2.begin();
	for(; it1 != v1.end() && it2 != v2.end(); it1++, it2++) {
		int sum = *it1 + *it2;
		v3.push_back(sum);
	}
	for(; it1 != v1.end(); it1++) {
		v3.push_back(*it1);
	}
	for(; it2 != v2.end(); it2++) {
		v3.push_back(*it2);
	}
	vector<int>::iterator it3 = v3.begin();
	bool flg = false;
	for(; it3 != v3.end(); it3++) {
		if(*it3 > 9) {
			*it3 -= 10;
			if(it3 + 1 == v3.end()) {
				flg = true;
			} else {
				*(it3 + 1) += 1;
			}
		}
	}
	if(flg) {
		v3.push_back(1);
	}
	return v3;
}

void printv(vector<int> v) {
	vector<int>::reverse_iterator rit = v.rbegin();
	for(; rit != v.rend(); rit++) {
		cout << *rit;
	}
	cout << endl;
}

void f(int x) {
	if(!mem[x].empty()) {
		return;
	}
	if(m == x || m + 1 == x) {
		mem[x].push_back(1);
		return;
	}
	f(x - 1);
	f(x - 2);
	mem[x] = add(mem[x - 1], mem[x - 2]);
}

int main() {
	cin >> m >> n;
	f(n);
	printv(mem[n]);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值