hdu 5167(dfs)

Fibonacci

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


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, n<=10^9,问是否存在一系列斐波拉契数列中的数字使得这一系列斐波拉契数之积等于 n
题解:暴力搜索,但是要加剪枝,不然会超时,我们先从最大的斐波拉契数开始,如果能够除尽,那么下一个斐波拉契数必定不会大于当前这个数,所以可以在这里剪个枝,还是跑了700ms+
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long LL;
LL f[45];
bool flag;
void init(){
    f[0] = 0;
    f[1] = 1;
    for(int i=2;i<=45;i++){
        f[i] = f[i-1]+f[i-2];
    }

}
void dfs(LL ans,int step){
    if(ans==1){
        flag = true;
        return;
    }
    for(int i=3;i<=step;i++){
        if(ans<f[i]) break;
        if(ans%f[i]==0){
            if(flag) return;
            dfs(ans/f[i],i);
        }
    }
    return;
}
int main()
{
    init();
    int tcase;
    scanf("%d",&tcase);
    while(tcase--)
    {
        LL n;
        scanf("%lld",&n);
        if(n==0){
            printf("Yes
");
            continue;
        }
        flag = false;
        dfs(n,45);
        if(flag) printf("Yes
");
        else printf("No
");
    }

    return 0;
}

 -------------------------------------------------------------------------------------------------------------------------------------------------------

然后我把循环顺序改了,171msAC...

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long LL;
LL f[45];
bool flag;
void init(){
    f[0] = 0;
    f[1] = 1;
    for(int i=2;i<=45;i++){
        f[i] = f[i-1]+f[i-2];
    }

}
void dfs(LL ans,int step){
    if(ans==1){
        flag = true;
        return;
    }
    for(int i=step;i>=3;i--){
        if(ans%f[i]==0){
            if(flag) return;
            dfs(ans/f[i],i);
        }
    }
    return;
}
int main()
{
    init();
    int tcase;
    scanf("%d",&tcase);
    while(tcase--)
    {
        LL n;
        scanf("%lld",&n);
        if(n==0){
            printf("Yes
");
            continue;
        }
        flag = false;
        dfs(n,45);
        if(flag) printf("Yes
");
        else printf("No
");
    }

    return 0;
}
原文地址:https://www.cnblogs.com/liyinggang/p/5681823.html