用法

声明一个矩阵: matrix a;

支持 + , - , * , % , 下标访问和快速幂.

注意:为了方便debug,在不满足运算法则进行运算时会直接退出程序并输出 Matrix error!

默认矩阵大小为 Xsize , Ysize ,可自行修改
我也写了构造函数,可以用 matrix a(10,10) 来手动规定矩形的长和宽.

默认情况下矩阵内全为0,可以通过下标访问修改矩阵内元素的值.

默认情况下矩阵内元素类型为 int ,可以修改 #define type int 来修改元素类型.

默认情况下矩阵自动对 INT_MAX 取模,你也可以修改这个自动模数,在 const type mod = INT_MAX 处可以修改.

为了debug方便你可以直接 print(matrix) 来输出一个矩阵.

我内部是用一个 vector<vector<type>> 实现的矩阵(二维数组太不灵活了),常数有点大请见谅,但是我找不到更好的写法来实现矩阵了,如果有速度更快的办法可以私信我,我尽量更新( .

code

namespace Matrix
{
#define type int
const int Xsize = 80;
const int Ysize = 80;
const type mod = INT_MAX;
struct matrix
{
vector<vector<type>> a;
int xlen, ylen;
matrix(int x=Xsize, int y=Ysize)
{
xlen = x, ylen = y;
a.resize(x+1);
for(int i = 1; i <= x; i++)
{
a[i].resize(y+1);
a[i].assign(y+1, 0);
}
}
vector<type>& operator [] (int x)
{
return a[x];
}
};
void throw_error()
{
cout << "Matrix error!";
std::exit(0);
}
matrix operator + (matrix a, matrix b)
{
if(a.xlen != b.xlen or a.ylen != b.ylen)
throw_error();
for(int i = 1; i <= a.xlen; i++)
for(int j = 1; j <= a.ylen; j++)
(a[i][j] += b[i][j]) %= mod;
return a;
}
matrix operator - (matrix a, matrix b)
{
if(a.xlen != b.xlen or a.ylen != b.ylen)
throw_error();
for(int i = 1; i <= a.xlen; i++)
for(int j = 1; j <= a.ylen; j++)
(a[i][j] -= b[i][j]) %= mod;
return a;
}
matrix operator * (matrix a, matrix b)
{
if(a.ylen != b.xlen) throw_error();
matrix ans(a.xlen, b.ylen);
for(int i = 1; i <= a.xlen; i++)
for(int j = 1; j <= b.ylen; j++)
for(int k = 1; k <= a.ylen; k++)
(ans[i][j] += a[i][k]*b[k][j]) %= mod;
return ans;
}
matrix operator * (matrix a, type k)
{
for(int i = 1; i <= a.xlen; i++)
for(int j = 1; j <= a.ylen; j++)
(a[i][j] *= k) %= mod;
return a;
}
matrix operator % (matrix a, type k)
{
for(int i = 1; i <= a.xlen; i++)
for(int j = 1; j <= a.ylen; j++)
a[i][j] %= k;
return a;
}
matrix& operator += (matrix &a, matrix b){ return (a = a+b); }
matrix& operator -= (matrix &a, matrix b){ return (a = a-b); }
matrix& operator *= (matrix &a, matrix b){ return (a = a*b); }
matrix& operator *= (matrix &a, type k){ return (a = a*k); }
matrix& operator %= (matrix &a, type k){ return (a = a%k); }
matrix pow(matrix a, long long p, type k=mod)
{
if(a.xlen != a.ylen) throw_error();
matrix ans(a.xlen, a.ylen);
for(int i = 1; i <= a.xlen; i++)
ans[i][i] = 1;
for(; p; p >>= 1, (a *= a) %= k)
if(p&1) (ans *= a) %= k;
return ans;
}
void print(matrix a)
{
for(int i = 1; i <= a.xlen; i++)
{
for(int j = 1; j <= a.ylen; j++)
cout << a[i][j] << ' ';
cout << endl;
}
}
}
using namespace Matrix;