24-Fibonacci(dfs+剪枝)

http://acm.hdu.edu.cn/showproblem.php?pid=5167

                Fibonacci

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


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
 
Recommend
hujie   |   We have carefully selected several similar problems for you:  6263 6262 6261 6260 6259 
#include <iostream>
using namespace std;
int a[100];
int ct, flag;

void init(){
	a[0] = 0;
	a[1] = 1;
	ct += 2;
	for(int i = 2; a[i - 1] <= 1000000000; i++){  //条件写为a[i]<=100000000000就崩了,注意是先i++,再判断条件的,所以会死循环 
		a[i] = a[i - 1] + a[i - 2];
		ct++;
	}
}
void dfs(int n, int k){
	if(n == 1){
		flag = 1;
		return ;
	}
	for(int i = k; i >= 3; i--){
		if(a[i] > n){
			continue;
		}
		else if(n % a[i] == 0){
			dfs(n / a[i], i); //注意:不是k-1而是i 
		}
		if(flag)    //剪纸 
			return ;	
	}
}
int main(){
	std::ios::sync_with_stdio(false);
	int t, n;
	init(); 
	cin >> t;
	while(t--){
		cin >> n;
		if(n == 0 || n == 1){  //要特判 
			cout << "Yes" << endl;
		}
		else{
			flag = 0;
			dfs(n, ct - 1);
			if(flag){
				cout << "Yes" << endl;
			}			
			else{
				cout << "No" << endl;
			}
		}	
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/8681032.html