码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 4549

时间:2015-09-01 19:50:48      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

水题: 费马小定理+快速幂+矩阵快速幂

(第一次用到费马小定理)

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const LL MOD  = 1000000006;
const LL MOD1 = 1000000007;
struct Matrix
{
    LL NUM[2][2];
    Matrix operator + (const Matrix a) const
    {
        Matrix c;
        for(int i = 0; i < 2; ++i)
        {
            for(int j = 0; j < 2; ++j)
            {
                c.NUM[i][j] = NUM[i][j] + a.NUM[i][j];
            }
        }
        return c;
    }
    Matrix operator * (const Matrix a) const
    {
        Matrix c;
        for(int i = 0; i < 2; ++i)
        {
            for(int j = 0; j < 2; ++j)
            {
                c.NUM[i][j] = 0;
                for(int k = 0; k < 2; ++k)
                    c.NUM[i][j] = (c.NUM[i][j] + NUM[i][k] * a.NUM[k][j] % MOD) % MOD;
            }
        }
        return c;
    }
};

Matrix ppow(Matrix a, LL n)
{
    Matrix ret;
    for(int i =0 ; i< 2; ++i)
    {
        for(int j = 0; j < 2; ++j)
            ret.NUM[i][j] = i==j ? 1 : 0;
    }
    while(n)
    {
        if(n & 1) ret = ret * a;
        a = a * a;
        n >>= 1;
    }
    return ret;
}

LL Pow(LL a, LL n)
{
    LL ret = 1;
    while(n)
    {
        if(n & 1) ret =ret * a % MOD1;
        a = a * a % MOD1;
        n >>= 1;
    }
    return ret;
}

int main()
{
    LL a, b, n;
    Matrix E;
    E.NUM[0][0] = 1; E.NUM[0][1] = 1;
    E.NUM[1][0] = 1; E.NUM[1][1] = 0;
    while(cin >> a >> b >> n)
    {
        if(n == 0) cout << a << endl;
        else if(n == 1) cout << b << endl;
        else
        {
            n -= 1;
            Matrix tmp = ppow(E,n);
            LL na = tmp.NUM[0][1] , nb = tmp.NUM[0][0];
            LL ans = (Pow(a,na) * Pow(b,nb))%MOD1;
            cout << ans << endl;
        }
    }
    return 0;
}

HDU 4549

标签:

原文地址:http://www.cnblogs.com/aoxuets/p/4776518.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!