打了一个矩阵模板类
调了一整天都没搞懂为什么调试都调试不了QωQ
代码如下:
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int mod;
class matrix
{
private:
int **data,x,y;
public:
matrix()
{
x=y=0;
}
matrix(int row,int col)
{
x=row;y=col;
data=new int*[row+1];
for(int i=1;i<=row;i++)
data[i]=new int[col+1];
}
matrix(int Error_Code)
{
matrix Error_Matrix(0,0);
// return Error_Matrix;
}
matrix zero()
{
// if(x!=y)return matrix(0);
for(int i=1;i<=x;i++)
data[i][i]=1;
}
matrix(matrix &b)
{
x=b.x;y=b.y;
data=new int*[b.x+1];
for(int i=1;i<=x;i++)
{
data[i]=new int[b.y+1];
for(int j=1;j<=y;j++)
data[i][j]=b[i][j];
}
}
matrix operator +(matrix b)
{
// if(x!=b.x||y!=b.y)return matrix(0);
matrix ans(x,y);
ans.x=x;ans.y=y;
for(int i=1;i<=x;i++)
for(int j=1;j<=y;j++)
ans.data[i][j]=data[i][j]+b.data[i][j];
return ans;
}
matrix operator -(matrix b)
{
// if(x!=b.x||y!=b.y)return matrix(0);
matrix ans(x,y);
ans.x=x;ans.y=y;
for(int i=1;i<=x;i++)
for(int j=1;j<=y;j++)
ans.data[i][j]=data[i][j]-b.data[i][j];
return ans;
}
matrix operator *(matrix b)
{
// if(y!=b.x)return matrix(0);
matrix ans(x,b.y);
for(int i=1;i<=x;i++)
for(int j=1;j<=b.y;j++)
for(int k=1;k<=y;k++)
(ans.data[i][j]+=data[i][k]*b.data[k][j]%mod)%=mod;
return ans;
}
int* operator [](const int pos)
{
return data[pos];
}
matrix& operator *=(matrix &b)
{
*this=(*this)*b;
return *this;
}
};
matrix pow(matrix base,int exp)
{
matrix x(base),a(2,2);
a.zero();
while(exp)
{
if(exp&1)a*=x;
exp>>=1;x*=x;
}
return a;
}
int main()
{
int n;
matrix a(2,2);
a[1][1]=a[1][2]=a[2][1]=1;
scanf("%d%d",&n,&mod);
printf("%d",pow(a,n)[1][1]);
return 0;
}
每一次调用[]
运算符时都会报错,访问到不应该访问的内存位置