Description
Fibonacci数列,定义如下:
f(1)=f(2)=1
f(n)=f(n-1)+f(n-2) n>=3。
计算第n项Fibonacci数值。
f(1)=f(2)=1
f(n)=f(n-1)+f(n-2) n>=3。
计算第n项Fibonacci数值。
Input
输入第一行为一个整数N,接下来N行为整数Pi(1<=Pi<=1000)。
Output
输出为N行,每行为对应的f(Pi)。
Sample Input
5 1 2 3 4 5
Sample Output
1 1 2 3 5
套用大数加法模板,这种题比较难判断的地方是,如何确定改题是大数题
AC代码:
#include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<string> #include<cmath> #include<iomanip> #define maxn 10000 #define MAX 10000 using namespace std; struct node { string a; }; //大数加法模板 string add(string s1, string s2) { if(s1.length() < s2.length()) { //确保s1的位数永远大于等于s2的位数 string temp = s1; s1 = s2; s2 = temp; } int i, j; for(i=s1.length()-1, j=s2.length()-1; i>=0; --i, --j) { s1[i] = char(s1[i] + (j>=0? s2[j]-'0': 0)); //处理了s1,s2位数不同的情况和相同的情况 if(s1[i] - '0' >= 10) { //当出现进位的时候 s1[i] = char((s1[i] - '0')%10 + '0'); if(i) ++s1[i-1]; else s1 = '1' + s1; //解决当加到最高位有进位的时候 } } return s1; } int main() { node f[1001]; f[1].a = "1"; f[2].a = "1"; for(int i=3; i<=1000; ++i) { f[i].a = add(f[i-1].a, f[i-2].a); } int n, t;; scanf("%d",&n); while(n--) { scanf("%d",&t); cout<<f[t].a<<endl; } return 0; }