山东省第七届ACM大学生程序设计竞赛-Fibonacci
2016-06-19 11:05
579 查看
Fibonacci
Time Limit: 2000ms Memory limit: 131072K 有疑问?点这里^_^
题目描述
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.
输入
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<=109).
输出
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 aremultiple ways, you can output any of them.
示例输入
4
5
6
7
100
示例输出
5=5
6=1+5
7=2+5
100=3+8+89
提示
来源
“浪潮杯”山东省第七届ACM大学生程序设计竞赛题目意思:
给一个数N,求出是否有互不相邻的几个斐波那契数相加等于N。解题思路:
先找到满足小于等于n的最大斐波那契数,再依次递减寻找下一个满足条件的数。#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> using namespace std; #define MAXN 1001 int f[50],a[50];//分别表示保存斐波那契数列、求和的各项 void fun()//斐波那契数列打表 { f[0]=1,f[1]=2; for(int i=2; i<50; ++i) f[i]=f[i-1]+f[i-2]; } int main() { ios::sync_with_stdio(false); cin.tie(0); int t,flag,cnt; cin>>t; fun(); memset(a,0,sizeof(a)); while(t--) { int i,j,n; flag=cnt=0; cin>>n; for(i=0; i<50; ++i)//找到满足小于等于n的最大斐波那契数 if(n<=f[i]) { cout<<n<<"="; if(n==f[i]) a[cnt++]=f[i]; else { --i; a[cnt++]=f[i]; } flag=1;//flag标记是否存在求和序列 n-=f[i]; break; } for(j=i-1; j>=0; --j)//i-1是因为不能相邻 { if(n>=f[j]) { n-=f[j]; a[cnt++]=f[j]; --j; } } if(!flag) cout<<"-1"<<endl;//不存在 else { for(i=--cnt; i>0; --i) cout<<a[i]<<"+"; cout<<a[0]<<endl; } } return 0; } /* 4 5 6 7 100 */
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性