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

矩阵快速幂

时间:2017-12-30 15:50:50      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:turn   pre   its   def   www   for   names   sizeof   ems   

https://www.luogu.org/problemnew/show/P3390

快速幂 + 矩阵

#include <bits/stdc++.h>

using namespace std;

#define LL long long

const LL mod = 1e9 + 7;
const int N = 110;

LL n, k;

struct JZ{
    LL m[N][N];
    JZ() {memset(m,0,sizeof m);}
    void clear() {for(int i = 1; i <= 100; i ++) m[i][i] = 1;}
};

JZ operator *(JZ a, JZ b) {
    JZ ret;
    for(int i = 1; i <= n; i ++)
        for(int j = 1; j <= n; j ++)
            for(int k = 1; k <= n; k ++)
                ret.m[i][j] = (ret.m[i][j] + a.m[i][k] * b.m[k][j]) % mod;
    return ret; 
}

JZ ksm(JZ a, LL p){
    JZ ret; ret.clear();
    while(p){
        if(p & 1) ret = ret * a;
        a = a * a;
        p >>= 1;
    }
    return ret;
}

int main()
{
    cin >> n >> k;
    JZ a;
    for(int i = 1; i <= n; i ++)
        for(int j = 1; j <= n; j ++)
            cin >> a.m[i][j];
    JZ Ans = ksm(a, k);
    
    for (int i=1; i<=n; i++,puts("")) 
        for (int j=1; j<=n; j++) 
            printf("%lld ",Ans.m[i][j]);    
    return 0;
}

 

矩阵快速幂

标签:turn   pre   its   def   www   for   names   sizeof   ems   

原文地址:https://www.cnblogs.com/shandongs1/p/8149933.html

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