poj3070 Fibonacci(矩阵快速幂)

矩阵的快速幂算法



/*
#include<iostream>
using namespace std;
typedef unsigned long long ll;
#define MOD 10000
struct Mat
{

};
ll f[2];
ll fib(int n)
{   //int f[2];
    f[1]=0;f[2]=1;
    for(int  i=2;i<=n;i++)
    {
        f[0]=f[1]%MOD;
        f[1]=f[2]%MOD;
        f[2]=(f[1]+f[0])%MOD;
    }
    return f[2];
}
int main()
{   int n;
    while(cin>>n&&n!=-1)
    {   if(n==0)
        cout<<0<<endl;
        else if(n==1)
            cout<<1<<endl;
        else
        cout<<fib(n)%MOD<<endl;
    }

    return 0;
}*/

#include <cstdio>
#include <iostream>
#include<cstdlib>
using namespace std;
typedef unsigned long long ll;
const int MOD = 10000;
/*
struct matrix
{
    int m[2][2];
}ans, base;

matrix multi(matrix a, matrix b)
{
    matrix tmp;
    for(int i = 0; i < 2; ++i)
    {
        for(int j = 0; j < 2; ++j)
        {
            tmp.m[i][j] = 0;
            for(int k = 0; k < 2; ++k)
                tmp.m[i][j] = (tmp.m[i][j]+ a.m[i][k] * b.m[k][j])%MOD ;
        }
    }
    return tmp;
}
int fast_mod(int n)  // 求矩阵 base 的  n 次幂
{
    base.m[0][0] = base.m[0][1] = base.m[1][0] = 1;
    base.m[1][1] = 0;
    ans.m[0][0] = ans.m[1][1] = 1;  // ans 初始化为单位矩阵
    ans.m[0][1] = ans.m[1][0] = 0;
    while(n)
    {
        if(n & 1)  //实现 ans *= t; 其中要先把 ans赋值给 tmp,然后用 ans = tmp * t
        {
            ans = multi(ans, base);
        }
            base = multi(base, base);
        n >>= 1;
    }
    return ans.m[0][1];
}*/
struct Mat {    ll mat[2][2];};
Mat operator * (Mat a, Mat b) {
    Mat c;
    memset(c.mat, 0, sizeof(c.mat));
    int i, j, k;
    for(k = 0; k < 2; ++k) {
        for(i = 0; i < 2; ++i) {
            if(a.mat[i][k] <= 0)  continue;
            for(j = 0; j < 2; ++j) {
                if(b.mat[k][j] <= 0)    continue;
                c.mat[i][j] =( c.mat[i][j]+a.mat[i][k] * b.mat[k][j])%MOD;
            }
        }
    }
    return c;
}
Mat operator ^ (Mat a, int k)
 {
    Mat c;
    int i,j;
    for(i=0;i<2;i++)
        for(j=0;j<2;j++)
        c.mat[i][j]=(i==j);
    for(;k;k>>=1)
    {   if(k&1) c=c*a;
        a=a*a;

    }
    return c;
}
int main()
{   Mat A,B;
    A.mat[0][0]=1;
    A.mat[0][1]=1;
    A.mat[1][0]=1;
    A.mat[1][1]=0;
    int n;
    while(cin>>n && n != -1)
    {       B=A^n;
        cout<<B.mat[1][0]%MOD<<endl;
    }
    return 0;
}


你可能感兴趣的:(poj3070 Fibonacci(矩阵快速幂))