跳到正文

个人记录

矩阵

ysy11约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年5月14日
收录
2026年4月29日
更新
2026年11月13日
篇幅
约 3 分钟

版本

  1. v2当前
  2. v1
C++
const ull matl=300;
void exgcd(ll a,ll b,ll &x,ll &y)
{
	if(!b)
	{
		x=1;
		y=0;
		return ;
	}
	exgcd(b,a%b,y,x);
	y-=a/b*x;
}
ll inv(ll a,const ll mod)
{
	ll x,y;
	exgcd(a,mod,x,y);
	x=(x%mod+mod)%mod;
	return x;
}
struct mat
{
	ll a[matl][matl];
	mat(bool x=0)
	{
		for(int i=0;i<matl;i++)
		{
			for(int j=0;j<matl;j++)
			{
				a[i][j]=0;
			}
		}
		if(!x)return ;
		for(int i=0;i<matl;i++)
		{
			a[i][i]=1;
		}
	}
	mat operator *(const mat& y)const
	{
		mat ans;
		for(register int i=0;i<matl;i++)
		{
			for(register int j=0;j<matl;j++)
			{
				for(register int k=0;k<matl;k++)
				{
					ans.a[i][j]+=a[i][k]*y.a[k][j]%MOD;
					ans.a[i][j]%=MOD;
				}
			}
		}
		return ans;
	}
	void operator *=(const mat& y)
	{
		*this=*this*y;
	}
	void ask()const
	{
		for(register int i=0;i<matl;i++)
		{
			for(register int j=0;j<matl;j++)
			{
				cout<<a[i][j]<<" ";
			}
			cout<<"\n";
		}
	}
	ll det(ll n)
	{
		mat ttt=*this;
		ll ans=1;
		for(int i=0;i<n;i++)
		{
			ll t=-1;
			for(int j=i;j<n;j++)
			{
				if(ttt.a[j][i])
				{
					t=j;
					break;
				}
			}
			if(t<0)return 0;
			if(t!=i)
			{
				ans=MOD-ans;
				swap(ttt.a[i],ttt.a[t]);
			}
			for(int j=i+1;j<n;j++)
			{
				ll tt=ttt.a[j][i]*inv(ttt.a[i][i],MOD)%MOD;
				for(int k=i;k<n;k++)
				{
					ttt.a[j][k]+=MOD-ttt.a[i][k]*tt%MOD;
					ttt.a[j][k]%=MOD;
				}
			}
			ans*=ttt.a[i][i];
			ans%=MOD;
		}
		return ans;
	}
};
mat pow(mat x,ll y)
{
	mat ans(1);
	while(y)
	{
		if(y&1)
		{
			ans*=x;
		}
		x*=x;
		y>>=1;
	}
	return ans;
}
原文