【POI2012】【BZOJ2796】Fibonacci Representation

本文介绍了一种利用Fibonacci数列进行数字分解的方法,并通过递归实现,优化了求解过程。对于每个查询,算法能够以最小数量的Fibonacci数来表示目标数字,展示了解决复杂数学问题的有效策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值