矩阵快速幂


矩阵乘法:
  行列式的概念:矩阵A=n*m,则称n为行,m为列。
  矩阵乘法的要求:A*B时:A=n*k,B=k*m。A的列等于B的行。新矩阵=n*m。
  新矩阵第n行,第m列的元素=A的第n行元素*B的第m列元素的乘积的和。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int mod=1e9+7;
struct mat{
    ll a[2][2];
};
mat matc(mat x,mat y){
    mat res;
    memset(res.a,0,sizeof(res.a));//important
    for(int i=0;i<2;i++)
       for(int j=0;j<2;j++)
          for(int k=0;k<2;k++)
               res.a[i][j]=(res.a[i][j]+x.a[i][k]*y.a[k][j])%mod;
    return res;           
}
inline int pow(int n){
    mat c,res;
    memset(res.a,0,sizeof(res.a));
    c.a[0][0]=1; c.a[0][1]=1;
    c.a[1][0]=1; c.a[1][1]=0;
    for(int i=0;i<n;i++) res.a[i][i]=1;//单位矩阵 
    while(n){
        if(n&1) res=matc(res,c);
        c=matc(c,c);
        n>>=1;
    }
    return res.a[0][1];
}
int main(){
    int n;
    scanf("%d",&n);
    cout<<pow(n);
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM