码迷,mamicode.com
首页 > 其他好文 > 详细

Fibonacci

时间:2018-10-04 13:44:28      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:view   tput   pid   each   htm   HERE   while   test   als   

题目链接

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("\n");
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\n");
48         }
49     }
50     return 0;
51 }
View Code

 

Fibonacci

标签:view   tput   pid   each   htm   HERE   while   test   als   

原文地址:https://www.cnblogs.com/Luckykid/p/9742044.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!