HDU 5167 (dfs || STL)

Fibonacci

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


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
 

Source
 


题意:

给你一个数n(1<=n<=1000 000 000),判断n的因子能否全部由斐波那契数列中的数组成。


分析:

方法一:可以知道在1~n范围内的斐波那契数只有45个,所以直接dfs搜索因子即可(刚开始一直TLE。。后来发现不需每次都要45个全搜,可以从大到小搜,如果那个数不符合时,后面就不用再搜那个数了)。


code:

#include<stdio.h>
#define N 45
int f[N]={0,1};

int dfs(int k, int fact)
{
    if(fact == 1 || fact == 0) return 1;
    for(int i=k; i>=3; i--)
        if(fact%f[i] == 0)
            if(dfs(i,fact/f[i])) return 1;
    return 0;
}

int main()
{
    int T, n;

    for(int i=2; i<N; i++)
        f[i] = f[i-1]+f[i-2];
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d", &n);
        puts(dfs(N-1,n) ? "Yes" : "No");
    }
    return 0;
}

第二种方法:把那45个数互相乘啊乘啊乘,在1e9范围内的所有可能的数都找出来,然后看有没有等于n的;

#include<stdio.h>
#include<vector>
#include<set>
using namespace std;
#define N 45
int main()
{
    int T, n, f[N] = {0,1};

    for(int i=2; i<N; i++)
        f[i] = f[i-1]+f[i-2];
    set<int> s;
    set<int>::iterator it;
    vector<int> v;
    s.insert(1);
    for(int i=3; i<N; i++)
    {
        v.clear();
        for(long long m=f[i]; m<=1e9; m*=f[i])
        {
            for(it=s.begin(); it!=s.end(); it++)
            {
                if(m*(*it) > 1e9) break;
                v.push_back(m*(*it));
            }
        }
        for(int i=0; i<v.size(); i++)
            s.insert(v[i]);
    }
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d", &n);
        if(s.find(n) != s.end() || n==0) puts("Yes");
        else puts("No");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值