Fibonacci
Posted luckykid
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Fibonacci相关的知识,希望对你有一定的参考价值。
Problem Description
Fibonacci numbers are well-known as follow:
Now given an integer N, please find out whether N can be represented as the sum of several Fibonacci numbers in such a way that the sum does not include any two consecutive Fibonacci numbers.
Input
Multiple test cases, the first line is an integer T (T<=10000), indicating the number of test cases.
Each test case is a line with an integer N (1<=N<=10^9).
Output
One line per case. If the answer don’t exist, output “-1” (without quotes). Otherwise, your answer should be formatted as “N=f1+f2+…+fn”. N indicates the given number and f1, f2, … , fn indicating the Fibonacci numbers in ascending order. If there are multiple ways, you can output any of them.
Sample Input
4
5
6
7
100
Sample Output
5=5
6=1+5
7=2+5
100=3+8+89
Source
“浪潮杯”山东省第七届ACM大学生程序设计竞赛
代码:
1 #include<bits/stdc++.h> 2 using namespace std; 3 //一般就是定义为最大的变量 + 10,开始定义为visited[44]错了多少次,我吉吉都付不清了...... 4 long long int a,b,k,flag,f[50],fx[50],visited[50]; 5 void dfs(long long int ans){ 6 //由于只需要输出一组,所以定义一个flag变量,如果已经进行完一组,直接返回 7 if(flag) 8 return; 9 if(ans == b){ 10 flag = 1; 11 printf("%lld=",b); 12 for(int i = k - 1;i >= 0;i--){ 13 if(i == k - 1) 14 printf("%lld",fx[i]); 15 else 16 printf("+%lld",fx[i]); 17 } 18 printf(" "); 19 return; 20 } 21 for(int i = 44;i >= 1;i--){//从大往小找,节省时间 22 //题目要求不能连续,即必须相差一个,因此!visited[i - 1] && !visited[i + 1]也必须要判断 23 if(ans + f[i] <= b && !visited[i] && !visited[i - 1] && !visited[i + 1]){ 24 visited[i] = true; 25 fx[k++] = f[i]; 26 dfs(ans + f[i]); 27 if(flag)//如果进行完一组,直接返回,不用向下递归 28 return; 29 visited[i] = false; 30 k--;//回溯 31 } 32 } 33 return; 34 } 35 int main(){ 36 f[1] = 1,f[2] = 2; 37 for(int i = 3;i <= 44;i++) 38 f[i] = f[i - 1] + f[i - 2];//先进行打表 39 while(~scanf("%lld",&a)){ 40 while(a--){ 41 memset(fx,0,sizeof(fx)); 42 memset(visited,0,sizeof(visited)); 43 scanf("%lld",&b); 44 flag = 0,k = 0; 45 dfs(0); 46 if(!flag) 47 printf("-1 "); 48 } 49 } 50 return 0; 51 }
以上是关于Fibonacci的主要内容,如果未能解决你的问题,请参考以下文章