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

POJ3070:Fibonacci——题解

时间:2018-01-30 23:00:21      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:乘法   col   algo   lld   stream   blog   ret   queue   get   

http://poj.org/problem?id=3070

题目大意:求Fibonacci数列第n项,对10000取模。

矩阵乘法板子题……实在不知道写什么了。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
typedef long long ll;
ll n,m=10000;
struct node{
    ll g[4][4];
}f,res;
void buildI(node &x){//构造单位矩阵
    for(int i=1;i<=2;i++){
        for(int j=1;j<=2;j++){
            if(i==j)x.g[i][j]=1LL;
            else x.g[i][j]=0LL;
        } 
    }
    return;
}
void multi(node &x,node &y,node &z){//z=x*y
    memset(z.g,0,sizeof(z.g));
    for(int i=1;i<=2;i++){
        for(int j=1;j<=2;j++){
            if(x.g[i][j]){
                for(int k=1;k<=2;k++){
                    z.g[i][k]+=x.g[i][j]%m*y.g[j][k]%m;
                    z.g[i][k]%=m;
                }
            }
        }
    }
    return;
}
void qpow(ll k){
    buildI(res);
    node tmp=f,t;
    while(k!=0){
        if(k&1){
            multi(res,tmp,t);
            res=t;
        }
        multi(tmp,tmp,t);
        tmp=t;
        k>>=1;
    }
    return;
}
ll solve(){
    if(n==0)return 0LL;
    if(n<=2)return 1LL;
    qpow(n-2);
    ll ret=res.g[1][1]%m+res.g[2][1]%m;
    return ret%m;
}
int main(){
    while(scanf("%lld",&n)!=EOF){
        if(n==-1)break;
        f.g[1][1]=1;f.g[1][2]=1;
        f.g[2][1]=1;f.g[2][2]=0;
        ll res=solve();
        printf("%lld\n",res);
    }
    return 0;
}

+++++++++++++++++++++++++++++++++++++++++++

+本文作者:luyouqi233。               +

+欢迎访问我的博客:http://www.cnblogs.com/luyouqi233/+

+++++++++++++++++++++++++++++++++++++++++++

POJ3070:Fibonacci——题解

标签:乘法   col   algo   lld   stream   blog   ret   queue   get   

原文地址:https://www.cnblogs.com/luyouqi233/p/8387233.html

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