[POI 2012]Fibonacci Representation(记忆化DFS)

21 篇文章 0 订阅

题目链接

http://main.edu.pl/en/archive/oi/19/roz

题目大意

给出一个数字,用FIB数列各项加加减减来得到。例如
10=5+5
19=21-2
17=13+5-1
1070=987+89-5-1
T 次询问数字n,问至少要加减多少次才能得到数字 n

思路

显然对于一个数字n而言,我们要么对它减去一个最大的比 n 小的数字,要么用一个最小的比它大的数字减去它来得到新的数字,这样做显然能让步数最少。我们可以记忆化DFS,从数字n开始,每次枚举被某个数减和减去某个数来得到两个不同的转移,然后取最优解。

代码

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <map>

#define MAXN 11000

using namespace std;

typedef long long int LL;

LL f[MAXN];
map<LL,int>dp;
int tot=0;

int DFS(LL n)
{
    if(dp[n]) return dp[n];
    int p=lower_bound(f+1,f+100+1,n)-f;
    if(f[p]==n) return 1;
    return dp[n]=min(DFS(n-f[p-1]),DFS(f[p]-n))+1;
}

int main()
{
    int T;
    LL n;
    scanf("%d",&T);
    f[1]=f[2]=1;
    tot=2;
    for(int i=3;f[tot]<=2e18;i++) f[++tot]=f[i-1]+f[i-2];
    while(T--)
    {
        scanf("%lld",&n);
        printf("%d\n",DFS(n));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值