51nod1242 斐波那契数列的第N项

链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1242

题意:中文题。。

分析:矩阵快速幂加速求斐波那契裸题。

代码:

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<bitset>
#include<math.h>
#include<cstdio>
#include<vector>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
const int N=2000010;
const int MAX=151;
const int MOD1=1000007;
const int MOD2=100000009;
const double EPS=0.00000001;
typedef long long ll;
const ll MOD=1000000009;
const ll INF=10000000010;
typedef unsigned long long ull;
struct Martx {
    ll x[3][3];
};
Martx mulmar(Martx A,Martx B) {
    Martx ret;
    memset(ret.x,0,sizeof(ret.x));
    for (int i=1;i<3;i++)
        for (int j=1;j<3;j++)
            for (int k=1;k<3;k++)
            ret.x[i][j]=(ret.x[i][j]+A.x[i][k]*B.x[k][j])%MOD;
    return ret;
}
Martx q_pow(int n,Martx A) {
    Martx ret;
    ret.x[1][2]=ret.x[2][1]=0;
    ret.x[1][1]=ret.x[2][2]=1;
    while (n) {
        if (n&1) ret=mulmar(ret,A);
        A=mulmar(A,A);
        n>>=1;
    }
    return ret;
}
int main()
{
    ll n;
    Martx A,B;
    A.x[1][1]=1;A.x[1][2]=1;
    A.x[2][1]=1;A.x[2][2]=0;
    while (scanf("%lld", &n)!=EOF) {
        n%=MOD-1;
        if (n==0) { printf("0\n");return 0; }
        if (n==1||n==2) { printf("1\n");return 0; }
        n-=2;B=q_pow(n,A);
        printf("%lld\n", ((B.x[1][1]+B.x[1][2])%MOD+MOD)%MOD);
    }
    return 0;
}


你可能感兴趣的:(51nod1242 斐波那契数列的第N项)