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

poj3070Fibonacci 矩阵快速幂

时间:2016-05-16 21:33:43      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:http://poj.org/problem?id=3070

code:

//矩阵快速幂
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define Mod 10000
using namespace std;
typedef struct juzhen{
    int a11,a12,a21,a22;
}JZ;
JZ quickpow(JZ s,int n)
{
    JZ base = s;
    // printf("%d %d\n%d %d\n",base.a11,base.a12,base.a21,base.a22);
    int ta11,ta12,ta21,ta22;
    s.a11 = s.a22 = 1;
    s.a12 = s.a21 = 0;
    while(n)
    {
        if((n & 1))
        {
            ta11 = s.a11*base.a11 + s.a12*base.a21;
            ta12 = s.a11*base.a12 + s.a12*base.a22;
            ta21 = s.a21*base.a11 + s.a22*base.a21;
            ta22 = s.a21*base.a12 + s.a22*base.a22;
            s.a11 = ta11 % Mod;
            s.a12 = ta12 % Mod;
            s.a21 = ta21 % Mod;
            s.a22 = ta22 % Mod;
        }
        ta11 = base.a11*base.a11 + base.a12*base.a21;
        ta12 = base.a11*base.a12 + base.a12*base.a22;
        ta21 = base.a21*base.a11 + base.a22*base.a21;
        ta22 = base.a21*base.a12 + base.a22*base.a22;
        base.a11 = ta11 % Mod;
        base.a12 = ta12 % Mod;
        base.a21 = ta21 % Mod;
        base.a22 = ta22 % Mod;
        n >>= 1;
    }
   // printf("%d %d\n%d %d\n",s.a11,s.a12,s.a21,s.a22);
    return s;
}
int main()
{
    int n;
    JZ s,e;
    s.a11 = s.a12 = s.a21 =  1;
    s.a22 = 0;
    while(cin >> n && n!=-1)
    {
        e = quickpow(s,n);
        //printf("%d %d\n%d %d\n",e.a11,e.a12,e.a21,e.a22);
        cout << e.a12 << endl;
    }
    return 0;
}

 

poj3070Fibonacci 矩阵快速幂

标签:

原文地址:http://www.cnblogs.com/zhangjialu2015/p/5499379.html

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