POJ 3070 Fibonacci

1、本题用到矩阵快速幂,注意矩阵乘法不满足交换律。

2、将矩阵写成类会更易编程。一次AC~

#include<cstdio>
#include<cstring>
using namespace std;
const int MAXN=2;
const int MAXM=2;
struct Matrix{
    int n,m;
 int a[MAXN][MAXM];
 void clear(){
  n=m=0;
  memset(a,0,sizeof(a));
 }
 Matrix operator + (const Matrix &b) const{
     Matrix temp;
  temp.n=n;temp.m=m;
  for(int i=0;i<n;i++)
   for(int j=0;j<m;j++)
    temp.a[i][j]=a[i][j]+b.a[i][j];
  return temp;
 }
 Matrix operator - (const Matrix &b) const{
     Matrix temp;
  temp.n=n;temp.m=m;
  for(int i=0;i<n;i++)
   for(int j=0;j<m;j++)
    temp.a[i][j]=a[i][j]-b.a[i][j];
  return temp;
 }
 Matrix operator * (const Matrix &b) const{
     Matrix temp;
  temp.clear();
  temp.n=n;temp.m=b.m;
  for(int i=0;i<n;i++)
   for(int j=0;j<b.m;j++)
    for(int k=0;k<m;k++)
     temp.a[i][j]+=a[i][k]*b.a[k][j];
  return temp;
 }
 Matrix operator % (const int mod) const{
     Matrix temp;
  temp.n=n;temp.m=m;
  for(int i=0;i<n;i++)
   for(int j=0;j<m;j++)
    temp.a[i][j]=a[i][j]%mod;
  return temp;
 }
};
Matrix pow_mod(Matrix A,int i,int mod){
    if(i==0){
    Matrix u;
    u.clear();
    u.n=MAXN;u.m=MAXM;
    u.a[0][0]=u.a[1][1]=1%mod;
    return u;
 }
 Matrix temp=pow_mod(A,i>>1,mod);
 temp=temp*temp%mod;
 if(i&1) temp=temp*A%mod;
 return temp;
}
Matrix A,An,X;
int main(){
 int n;
    A.n=MAXN;A.m=MAXM;
 A.a[0][0]=0;
 A.a[0][1]=A.a[1][0]=A.a[1][1]=1;
 while(scanf("%d",&n)==1){
     if(n==-1) break;
        An=pow_mod(A,n,10000);
        Matrix X;
  X.n=MAXN;X.m=1;
  X.a[0][0]=0;X.a[1][0]=1;
  X=An*X;
  printf("%d\n",X.a[0][0]);
 }
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值