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

矩阵快速幂

时间:2017-03-06 22:21:57      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:memset   amp   art   ++   rac   blog   span   com   矩阵   

技术分享
#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

 

矩阵快速幂

标签:memset   amp   art   ++   rac   blog   span   com   矩阵   

原文地址:http://www.cnblogs.com/Bennetts/p/6512162.html

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