题解 SP31428 【FIBONOMIAL - Fibonacci Polynomial】

· · 题解

D(n,x)=\sum\limits_{i=1}^nF_ix^i =\sum\limits_{i=1}^n\frac{1}{\sqrt 5}\left(\left(\frac{1+\sqrt 5}{2}\right)^i-\left(\frac{1-\sqrt 5}{2}\right)^i\right)x^i =\frac{1}{\sqrt 5}\sum\limits_{i=1}^n\left(\frac{1+\sqrt 5}{2}\right)^ix^i-\left(\frac{1-\sqrt 5}{2}\right)^ix^i

直接扩域,使用等比数列求和计算即可。

时间复杂度 \Theta(T\log n)。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<vector>
#define ll long long
#define reg register
#define inf 0x3f3f3f3f
#define p 1000000007
#define inv2 500000004
using namespace std;

inline int add(int a,int b){
    return a+b>=p?a+b-p:a+b;
}

inline int dec(int a,int b){
    return a<b?a-b+p:a-b;
}

inline int poww(int a,int t){
    int res = 1;
    while(t){
        if(t&1) res = (ll)res*a%p;
        a = (ll)a*a%p;
        t >>= 1;
    }
    return res;
}

struct complex{
    int a,b;
    complex(int a=0,int b=0):a(a),b(b){}

    inline complex operator + (const complex& x) const{
        return complex(add(a,x.a),add(b,x.b));
    }

    inline complex operator - (const complex& x) const{
        return complex(dec(a,x.a),dec(b,x.b));
    }

    inline complex operator - (const int& x) const{
        return complex(dec(a,x),b);
    }

    inline complex operator * (const complex& x) const{
        return complex(((ll)a*x.a+5ll*b*x.b)%p,((ll)a*x.b+(ll)b*x.a)%p);
    }

    inline complex operator * (const int& x) const{
        return complex((ll)a*x%p,(ll)b*x%p);
    }

    friend inline complex operator / (const complex &x,const complex &y){
        complex res,z = y;
        if(z.b!=0) z.b = p-z.b;
        res = x*z;
        return res*poww(dec((ll)y.a*y.a%p,5ll*y.b*y.b%p),p-2);
    }
};

inline complex power(complex a,ll t){
    complex res = complex(1,0);
    while(t){
        if(t&1) res = res*a;
        a = a*a;
        t >>= 1;
    }
    return res;
}

inline complex sum(complex x,ll n){
    if(x.a==1&&x.b==0) return n;
    return (power(x,n+1)-1)/(x-1);
}

inline int solve(ll n,int x){
    complex A = complex(inv2,inv2)*x;
    complex B = complex(inv2,p-inv2)*x;
    A = sum(A,n)-sum(B,n);
    return A.b;
}

inline void read(ll &x){
    x = 0;
    char c = getchar();
    while(c<'0'||c>'9') c = getchar();
    while(c>='0'&&c<='9'){
        x = (x<<3)+(x<<1)+(c^48);
        c = getchar();
    }
}

void print(int x){
    if(x>9) print(x/10);
    putchar(x%10+'0');
}

int main(){
    int T,a;
    ll n,x;
    scanf("%d",&T);
    while(T--){
        read(n),read(x);
        a = x%p;
        print(solve(n,a)),putchar('\n');
    }
    return 0;
}