全新方法

· · 题解

设 f_x 为斐波那契数列的第 x 位。

则 f_x=f_2 \times f_{x-1}+f_1\times f_{x-2}。

再拆一步,则 f_x=(f_1+f_2)\times f_{x-2} + f_2 \times f_{i-3}=f_3\times f_{x-2} + f_2 \times f_{i-3}。

以此类推,f_x=(f_2+f_3)\times f_{x-3} + f_3 \times f_{i-4}=f_4\times f_{x-3} + f_3 \times f_{i-4}。

同理,我们就发现了规律,对于任意 1< v <x,f_x=f_{x-v-1}\times f_v+f_{x-v}\times f_{v+1}。

所以,我们就可以使用递推了。

定义一个数组 a,如果 a_x 有值,返回 a_x,否则向下递推。

可以发现,当 v=\lfloor \frac x 2 \rfloor 向下递推时,可以将时间复杂度降到很小。

代码如下:

#include<bits/stdc++.h>
using namespace std;
#define R read()
#define int long long
#define mid (l+r>>1)
inline int R{
    int re=0,fg=1;
    char c;
    while (1){
        c=getchar();
        if (('0'<=c and c<='9') or c=='-')  break;
    }
    if (c=='-') c='0',fg=-1;
    while (1){
        re=re*10+c-'0';
        c=getchar();
        if (!(('0'<=c and c<='9') or c=='-'))   break;
    }
    return re*fg;
}
map<int,int>mp;
int f(int x){
    if (!mp[x]) mp[x]=f(x/2+1)*f(x-x/2)+f(x/2)*f(x-x/2-1);
    return mp[x];
}
signed main(){
    mp[1]=mp[2]=1;//一定要赋值 不然会输出 0
    int T=R;
    while (T--)cout<<f(R)<<"\n"; 
}