文章目录
学着用类来弄的那种:
并且多了动态开二维数组、引用、友元函数friend等
#include"bits/stdc++.h"
using namespace std;
typedef long long LL;
const LL MOD=1e9+7;
class Matrix
{
public:
int _n;//矩阵大小
LL **A;//二维数组用来装矩阵
public:
Matrix (int n):_n(n)
{
A=new LL *[_n];
for(int i=0;i<n;i++)
{
A[i]=new LL[_n];
for(int j=0;j<n;j++)A[i][j]=0;//初始化为0
}
}
friend istream &operator>>(istream &in,const Matrix &B)//重载矩阵输入
{
for(int i=0;i<B._n;i++)for(int j=0;j<B._n;j++)in>>B.A[i][j];
return in;
}
friend ostream &operator<<(ostream &out,const Matrix &B)//重载矩阵输出
{
for(int i=0;i<B._n;i++)
{
for(int j=0;j<B._n;j++)out<<B.A[i][j],cout<<" ";
cout<<endl;
}
return out;
}
Matrix operator*(Matrix &other)//重载矩阵乘法
{
Matrix res=Matrix(_n);
for(int i=0;i<res._n;i++)
for(int j=0;j<res._n;j++)
for(int k=0;k<res._n;k++)
{
res.A[i][j]+=A[i][k]*other.A[k][j]%MOD;
res.A[i][j]%=MOD;
}
return res;
}
Matrix operator^(int b)//重载矩阵快速幂
{
Matrix res(_n),base(_n);
for(int i=0;i<_n;i++)res.A[i][i]=1;
for(int i=0;i<_n;i++)for(int j=0;j<_n;j++)base.A[i][j]=A[i][j];//我不知道类中怎么直接复制数组,就只有一个一个赋值了
while(b)
{
if(b&1)res=res*base;
base=base*base;
b>>=1;
}
return res;
}
};
int main()
{
Matrix A(3),B(3);
cin>>A;
B=A*A;
B=B^3;
cout<<"A:\n"<<A;
cout<<"B:\n"<<B;
}
/*
1 2 3
4 5 6
7 8 9
*/
没有用类的那种
这里我在重载输入那里就遇到了问题,跟上面不一样,不能加const,不是太懂为什么(ಥ_ಥ)
#include"bits/stdc++.h"
using namespace std;
typedef long long LL;
const LL MOD=1e9+7;
struct Matrix
{
int n;
LL a[10][10];
Matrix (int n):n(n)
{
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)a[i][j]=0;
}
};
Matrix operator*(Matrix A,Matrix B)
{
int n=A.n;
Matrix res(n);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
for(int k=0;k<n;k++)
{
res.a[i][j]+=(LL)A.a[i][k]*B.a[k][j]%MOD;
res.a[i][j]%=MOD;
}
return res;
}
Matrix operator^(Matrix A,int b)
{
int n=A.n;
Matrix res(n),base=A;
for(int i=0;i<n;i++)res.a[i][i]=1;
while(b)
{
if(b&1)res=res*base;
base=base*base;
b>>=1;
}
return res;
}
istream & operator>>(istream & in,Matrix &B)//重载矩阵输入,这里不能加const,跟类中的不一样,加了的话会输入很多次,我也不懂为什么
{
//cout<<"shuru"<<endl;//阔以添加这段话看
for(int i = 0; i < B.n; i++)for(int j = 0; j < B.n; j++)in>>B.a[i][j];
return in;
}
ostream &operator<<(ostream &out,const Matrix &B)//重载矩阵输出
{
for(int i=0;i<B.n;i++)
{
for(int j=0;j<B.n;j++)out<<B.a[i][j],cout<<" ";
cout<<endl;
}
return out;
}
int main()
{
Matrix A(3),B(3);
cin>>A;
B=A*A;
B=B^3;
cout<<"A:\n"<<A;
cout<<"B:\n"<<B;
}
/*
1 2 3
4 5 6
7 8 9
*/