luogu P1962 斐波那契数列

二次联通门 : luogu P1962 斐波那契数列

 

 

 

 

 
 
/*
    luogu P1962 斐波那契数列

    矩阵快速幂求feibonacii
    
    矩阵为
    1 1
    1 0
    做N - 2次方就好 
*/
#include <cstdio>

#define Mod 1000000007

#define Max 2

void read (long long &now)
{
    now = 0;
    register char word = getchar ();
    while (word < '0' || word > '9')
        word = getchar ();
    while (word >= '0' && word <= '9')
    {
        now = now * 10 + word - '0';
        word = getchar ();
    }
}


struct Martix_Data
{
    
    long long data[Max][Max];
    
    void Prepare ()
    {
        this->data[0][0] = 1;
        this->data[0][1] = 1;
        this->data[1][0] = 1;
        this->data[1][1] = 0;
    }
    
    Martix_Data operator * (const Martix_Data &now) const
    {
        Martix_Data res;
        
        for (register int i = 0; i < Max; i ++)
            for (register int j = 0; j < Max; j ++)
            {
                res.data[i][j] = 0;
                for (register int k = 0; k < Max; k ++)
                    res.data[i][j] = (res.data[i][j] + this->data[i][k] * now.data[k][j]) % Mod;
            }
        
        return res;
    }
    
};

Martix_Data operator ^ (Martix_Data &now, long long P)
{
    Martix_Data res;
    res.Prepare ();
    if (P == 1)
        res.data[0][0] = 1;
    else if (P == 0)
        res.data[0][0] = 0;
    else
        for (P -= 2; P; P >>= 1)
        {
            if (P & 1)
                res = res * now;
            now = now * now;
        }    
    
    return res;
}

int main (int argc, char *argv[])
{
    long long N;
    read (N);
    Martix_Data Answer;
    Answer.Prepare (); 
    
    Answer = Answer ^ N;
    
    printf ("%lld", Answer.data[0][0]);
    
    return 0;
}

 

posted @ 2017-06-21 21:06  ZlycerQan  阅读(202)  评论(0编辑  收藏  举报