C++ 彰雲嘉區複賽 106-3 費波南希數列

題目連結:e523: 106 彰雲嘉區複賽 – Q3 費波南希數列

用到最簡單DP和二分搜(都可以不用)

#include<iostream>
#include<algorithm>
using namespace std;

int main(){
    ios::sync_with_stdio(0);cin.tie(0);

    int n,f[200];
    cin>>n;

    f[0]=-1;f[1]=1;f[2]=1;
    for(int i=3;i<100;i++){
        f[i]=f[i-1]+f[i-2];
        if(f[i]<0) f[i]=0x3f3f3f3f;
    }

    while(n--){
        int a;
        cin>>a;
        int it=lower_bound(f,f+100,a)-f;
        if(f[it]==a){
            cout<<it;
        }else{
            cout<<-1;
        }
        cout<<"\n";
    }
    return 0;
}

發佈留言