矩阵快速幂 poj 3070

#include <iostream>
#include <cstdio>

using namespace std;
const int MOD = 10000;

struct Matrix
{
    int m[2][2];
};

Matrix Mul(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;
}

Matrix fast_mod(Matrix a, int m)
{
    if(m == 1) return a;
    Matrix tmp = fast_mod(a, m>>1);
    tmp = Mul(tmp, tmp);
    if(m & 1) return Mul(a, tmp);
    else return tmp;
}

int main()
{
    int n;
    while(~scanf("%d", &n) && n != -1)
    {
        if(!n) {
                cout<<0<<endl;
                continue;
        }
        Matrix ans;
        ans.m[0][0] = ans.m[0][1] = ans.m[1][0] = 1, ans.m[1][1] = 0;
        ans = fast_mod(ans, n);
        cout<<ans.m[0][1]<<endl;
    }
    return 0;
}

你可能感兴趣的:(ACM,poj)