Description
Fib数列0,1,1,2,3,5,8,13,21。
给出一个数字,用FIB数列各项加加减减来得到。例如
10=5+5
19=21-2
17=13+5-1
1070=987+89-5-1
Input
In the first line of the standard input a single positive integer is given (1 <=P<=10) that denotes the number of queries. The following lines hold a single positive integer K each 1<=K<=10^17.
Output
For each query your program should print on the standard output the minimum number of Fibonacci numbers needed to represent the number k as their sum or difference.
Sample Input
1
1070
Sample Output
4
HINT
Source
这种题都是一样的,考虑递归然后Fib数分解就行了
只不过多了个减号
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<map>
#define LL long long
#define MAXINT 1LL<<62
using namespace std;
int T;
LL n,fib[100]={1,1};
map<LL,int> f;
int get_ans(LL x)
{
if (f[x]) return f[x];
int pos=lower_bound(fib,fib+88,x)-fib;
if (fib[pos]==x) return 1;
return f[x]=min(get_ans(x-fib[pos-1]),get_ans(fib[pos]-x))+1;
}
int main()
{
scanf("%d",&T);
for (int i=2;i<=89;i++) fib[i]=fib[i-1]+fib[i-2];
while (T--) cin>>n,printf("%d\n",get_ans(n));
}
本文介绍了一种利用Fibonacci数列进行数字分解的方法,并通过递归实现,优化了求解过程。对于每个查询,算法能够以最小数量的Fibonacci数来表示目标数字,展示了解决复杂数学问题的有效策略。
613

被折叠的 条评论
为什么被折叠?



