0
已采纳
把模板题模板化,会使main主函数显得非常优美。
简单说一下矩阵乘法吧,
假设我们有一个n行m列的矩阵a,和m行n列的矩阵b,设a*b后的结果为矩阵c,
则c的第i行第j列的数字就是第i行的每一列的a[i][k]与每一行的第j列的b[k][j]的乘积进行累和。
楼下dalao的图确实画的很好,可以结合他的图理解我的这句话。
参考代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long LL;
const LL Mod=1e9+7;
int n;
LL k;
struct Matrix{
static const int N=101;
int n;
LL h[N][N];
void clear(int n){
this->n=n;
memset(h,0,sizeof(h));
}
friend ostream& operator << (ostream&,Matrix&);
friend istream& operator >> (istream&,Matrix&);
Matrix operator * (const Matrix &t) const{
Matrix b;b.clear(n);
for (int i=1;i<=n;i++)
for (int j=1;j<=n;j++){
LL sum=0;
for (int k=1;k<=n;k++)
sum+=h[i][k]*t.h[k][j],sum%=Mod;
b.h[i][j]=sum;
}
return b;
}
Matrix operator ^ (LL k)const {
Matrix t=(*this),ans=(*this);
for (k--;k;k>>=1,t=t*t)
if (k&1)ans=ans*t;
return ans;
}
}a;
istream& operator >> (istream& input,Matrix &x){
for (int i=1;i<=x.n;i++)
for (int j=1;j<=x.n;j++)
input>>x.h[i][j];
return input;
}
ostream& operator << (ostream& output,Matrix &x){
for (int i=1;i<=x.n;i++){
for (int j=1;j<=x.n;j++)
output<<x.h[i][j]<<" ";
output<<endl;
}
return output;
}
int main(){
ios::sync_with_stdio(false);
cin>>n>>k;
a.clear(n);
cin>>a;
Matrix ans=a^k;
cout<<ans;
return 0;
}
0
0
0
