1. 程式人生 > 實用技巧 >矩陣快速冪模板

矩陣快速冪模板

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=105;
const int mod=1e9+7;
int n;
struct matrix {
    ll a[maxn][maxn];
    matrix() {
        memset(a,0,sizeof(a));
    }
    void build () {
        for (int i=1;i<=n;i++) a[i][i]=1;
    }
}wjm;
matrix operator
* (const matrix &x,const matrix &y) { matrix ans; for (int k=1;k<=n;k++) for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) ans.a[i][j]=(ans.a[i][j]+x.a[i][k]*y.a[k][j]%mod)%mod; return ans; } int main () { ll k; scanf("%d%lld",&n,&k);
for (int i=1;i<=n;i++) for (int j=1;j<=n;j++) scanf("%lld",&wjm.a[i][j]); matrix ans; ans.build(); do { if (k&1) ans=ans*wjm; wjm=wjm*wjm; k>>=1; }while (k); for (int i=1;i<=n;i++) { for (int j=1;j<=n;j++) printf("
%d ",ans.a[i][j]); printf("\n"); } }