bestcoder#28 1002 dfs

bestcoder#28 1002  dfs

Fibonacci

Accepts: 40
Submissions: 996
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 65536/65536 K (Java/Others)
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是否为一个或多个fib数的乘积
思路:dfs,从大数往小数遍历更省时
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<cstring>
#include<algorithm>
#include<vector>

using namespace std;

const int maxn=1000100;
const int INF=1000000000;

int T;
int n;
vector<int> fib;

inline int read()
{
    char c=getchar();
    while(c!='-'&&!isdigit(c)) c=getchar();
    int f=0,tag=1;
    if(c=='-'){
        tag=-1;
        f=getchar()-'0';
    }
    else f=c-'0';
    while(isdigit(c=getchar())) f=f*10+c-'0';
    return f*tag;
}

void creat_fib()
{
    fib.clear();
    fib.push_back(0);
    fib.push_back(1);
    int x=fib[0]+fib[1];
    while(x<=INF&&x>=0){
        fib.push_back(x);
        x=fib[fib.size()-1]+fib[fib.size()-2];
    }
}

bool dfs(int n,int t)
{
    if(t==2) return false;
    while(true){
        if(dfs(n,t-1)) return true;
        if(n%fib[t]) break;
        n/=fib[t];
    }
    if(n==1) return true;
    return false;
}

int main()
{
    cin>>T;
    creat_fib();
    while(T--){
        n=read();
        if(n==0||n==1||dfs(n,fib.size()-1)) printf("Yes\n");
        else printf("No\n");
    }
    return 0;
}
View Code

 

posted @ 2015-03-23 00:52  __560  阅读(224)  评论(0编辑  收藏  举报