hdu 5167 Fibonacci(DFS,剪枝,斐波那契)

本文探讨了如何解决HDU 5167 Fibonacci问题,通过使用深度优先搜索(DFS)并结合剪枝策略来避免超时错误。在枚举过程中,从最大数开始向下进行,同时对特殊情况0、1、2进行特判,以防止无限循环。

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

Fibonacci

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2391    Accepted Submission(s): 609


Problem Description
Following is the recursive definition of Fibonacci sequence:
Fi=01Fi1+Fi2i = 0i = 1i > 1

Now we need to check whether a number can be expressed as the product of numbers in the Fibonacci sequence.
 

Input
There is a number  T  shows there are  T  test cases below. ( T100,000 )
For each test case , the first line contains a integers n , which means the number need to be checked. 
0n1,000,000,000
 

Output
For each case output "Yes" or "No".
 

Sample Input
  
  
3 4 17 233
 

Sample Output
  
  
Yes No Yes
题意:问n是否能由多个斐波那契数相乘而来

思路:直接爆搜会TLE,所以这里有个剪枝技巧,我们从大小大枚举,这一次搜索选择了i,那么我们下次只需要枚举3~i即可,相等于从序列最大的数开始向下枚举。

注意0,1,2不能算进去,0,和1要特判,不然会死循环。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;
#define N 100000
long long f[N];
int flag,cnt;
long long n;
void init()
{
    f[0]=0;
    f[1]=1;
    cnt=2;
    for(; f[cnt-1]<=1000000000; cnt++)
        f[cnt]=f[cnt-1]+f[cnt-2];
}
void dfs(long long k,int num)
{
    if(k==1){
        flag=1;
        return;
    }
    for(int i=num;i>=3;i--)
        {
            if(f[i]>k) continue;
            if(k%f[i]==0)
            dfs(k/f[i],i);
            if(flag) return;
        }
}
int main()
{
    init();
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld",&n);
        if(!n||n==1) printf("Yes\n");
        else
        {
            flag=0;
            dfs(n,cnt-1);
            if(flag) printf("Yes\n");
            else printf("No\n");
        }
    }
    return 0;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值