矩阵快速幂

#include <cstdio>
#include<cstring>
#define SMod 1000000007
#define LL long long 
using namespace std;
int n;
LL k;
struct Matrix
{
    LL m[103][103];
    Matrix()
    {
        memset(m,0,sizeof(m));
        for(int i=1;i<=n+2;i++)
            m[i][i] = 1LL;
    }
};

Matrix Mul(Matrix a,Matrix b)
{
    Matrix res;
    int i,j,k;
    for(i=1;i<=n+2;i++)
    {
        for(j=1;j<=n+2;j++)
        {
            res.m[i][j] = 0;
            for(k=1;k<=n+2;k++)
                res.m[i][j] = (res.m[i][j]+(a.m[i][k]*b.m[k][j])%SMod + SMod)%SMod;
        }
    }
    return res;
}

Matrix fastm(Matrix a,LL b)
{
    Matrix res;
    while(b)
    {
        if(b&1)
            res = Mul(res,a);
        a = Mul(a,a);
        b >>= 1;
    }
    return res;
}
int main(){
    scanf("%d%lld",&n,&k);
    Matrix a;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            scanf("%d",&a.m[i][j]);
        }
    }
    a=fastm(a,k);
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            printf("%lld ",a.m[i][j]);
        }
        printf("\n");
    }
    return 0;
} 
View Code
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long LL;
const LL mod=1000000007;
LL n,p;
struct rew{
    LL a[101][101];
    rew operator * (const rew &x)const
    {
        rew res;
        for (int i=1;i<=n;i++)
            for (int j=1;j<=n;j++)
            {
                res.a[i][j]=0;
                for (int k=1;k<=n;k++)
                    res.a[i][j]=(res.a[i][j]+a[i][k]*x.a[k][j])%mod;
            }
        return res;
    }
    friend ostream &operator<<(ostream &os,const rew &c){
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                os<<c.a[i][j]<<" ";
            }
            os<<"\n";
        }
    }
    friend istream &operator>>(istream &is,rew &c){
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                is>>c.a[i][j];
            }
        }
    }
    //erator=(rew& e){ 
    //    for(int i=1;i<=n;i++){
    //    for(int j=1;j<=n;j++){
    //    a[i][j]=e.a[i][j];
        //}        
        //}   
}b1,b2;
int main(){
//    freopen("1.in","r",stdin);
//    freopen("2.out","w",stdout);
    int i,j;
    cin>>n>>p;
    cin>>b1;
    while(!(p&1)){
            b1=b1*b1;
            p>>=1;
    }
    b2=b1;
    p>>=1;
       b1=b1*b1;
    while(p>0){
        while(!(p&1)){
            b1=b1*b1;
            p>>=1;
        }
        b2=b2*b1;
           p>>=1;
           b1=b1*b1;
    }
    cout<<b2;
    return 0;
}
View Code

 

posted on 2017-03-06 21:46  bennetts  阅读(95)  评论(0编辑  收藏  举报

导航