hdu 5167 Fibonacci(DFS,剪枝,斐波那契)
阿新 • • 發佈:2019-01-01
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=⎧⎩⎨01Fi−1+Fi−2i = 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
For each test case , the first line contains a integers n , which means the number need to be checked.
0≤n≤1,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; }