矩阵快速幂
title: 矩阵快速幂
categories:
- ICPC
tags:
- null
abbrlink: 7f45ba65
date: 2024-05-16 00:00:00
debug:重载乘号的时候要把两个传进来的矩阵用起来
// Problem: P3390 【模板】矩阵快速幂
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P3390
// Memory Limit: 256 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <bits/stdc++.h>
using namespace std;
#define ll long long
# define int long long
#define ull unsigned long long
#define pii pair<int,int>
#define baoliu(x, y) cout << fixed << setprecision(y) << x
#define endl "\n"
#define debug1(x) cerr<<x<<" "
#define debug2(x) cerr<<x<<endl
const int N = 2e5 + 10;
const int M = 1e6 + 10;
const int inf = 0x3f3f3f3f;
const int mod =1e9+7;
const double eps = 1e-8;
int n, m;
int k;
struct matrix{
int c[101][101];
matrix(){memset(c,0,sizeof c);}
};
matrix operator*(matrix &a,matrix &b){
matrix res;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
for(int k=1;k<=n;k++){
res.c[i][j]+=(a.c[i][k]*b.c[k][j])%mod;
res.c[i][j]%=mod;
}
}
}
return res;
}
matrix pow(matrix &a,int k){
matrix res;
for(int i=1;i<=n;i++)res.c[i][i]=1;
while(k){
if(k&1)res=(res*a);
a=a*a;
k>>=1;
}
return res;
}
void solve(){
cin>>n>>k;
matrix a;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>a.c[i][j];
//cerr<<a.c[i][j]<<" ";
}
//cerr<<endl;
}
matrix ans=pow(a,k);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cout<<ans.c[i][j]<<" ";
}
cout<<endl;
}
}
signed main() {
cin.tie(0);
ios::sync_with_stdio(false);
int t;
//cin>>t;
t=1;
while (t--) {
solve();
}
return 0;
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 爱飞鱼的blog!