跳到正文

个人记录

勰码金牌学院 S1 课程 16&17. 高斯消元

_Sorasaki_Hina_约 83 分钟
原文

这是 2026年6月5日 存档的第 10 版,不是当前版本。查看当前版本

文章信息与版本

只有数学。

本质上是对矩阵进行初等行变换。

nn 元 11 次方程组

高斯消元可以对其进行求解(判断唯一解、无解、无穷解)。

一般来说,题面会给我们方程组的信息(增广矩阵):

A=[a1,1a1,2⋯a1,na2,1a2,2⋯a2,n⋮⋮⋱⋮an,1an,2⋯an,na1,n+1a2,n+1⋮an,n+1]A= \left [ \begin{array}{c|c} \begin{matrix} a_{1,1}&a_{1,2}&\cdots&a_{1,n}\\ a_{2,1}&a_{2,2}&\cdots&a_{2,n}\\ \vdots&\vdots&\ddots&\vdots&\\ a_{n,1}&a_{n,2}&\cdots&a_{n,n} \end{matrix}& \begin{matrix} a_{1,n+1}\\ a_{2,n+1}\\ \vdots\\ a_{n,n+1} \end{matrix} \end{array} \right ]

代表方程组:

{a1,1x1+a1,2x2+⋯+a1,nxn=a1,n+1a2,1x1+a2,2x2+⋯+a2,nxn=a2,n+1⋮an,1x1+an,2x2+⋯+an,nxn=an,n+1\begin{cases} a_{1,1}x_1 + a_{1,2}x_2 + \dots + a_{1,n}x_n &= a_{1,n+1}\\ a_{2,1}x_1 + a_{2,2}x_2 + \dots + a_{2,n}x_n &= a_{2,n+1}\\ &\vdots\\ a_{n,1}x_1 + a_{n,2}x_2 + \dots + a_{n,n}x_n &= a_{n,n+1} \end{cases}

由矩阵的性质,我们对其进行初等行变换,解是不变的。

这里主要有三种变换:

  1. 交换两行,解不变。
  2. 某行扩大 k,k≠0k,k\not=0 倍,解不变。
  3. 某行的 kk 倍加到另一行,解不变。

于是我们化为行阶梯型矩阵:

A′=[1b1,2⋯b1,n01⋯b2,n⋮⋮⋱⋮00⋯1b1,n+1b2,n+1⋮bn,n+1]A'= \left [ \begin{array}{c|c} \begin{matrix} 1&b_{1,2}&\cdots&b_{1,n}\\ 0&1&\cdots&b_{2,n}\\ \vdots&\vdots&\ddots&\vdots&\\ 0&0&\cdots&1 \end{matrix}& \begin{matrix} b_{1,n+1}\\ b_{2,n+1}\\ \vdots\\ b_{n,n+1} \end{matrix} \end{array} \right ]

行阶梯型矩阵:

  • 每一行从左向右看,第一个非零主元出现的列数随行数增加而严格递增。
  • 如果存在全为 00 的行,则必须位于矩阵最底部。
  • 为了计算方便,我们通常将每个非零行的主元化为 11。

然后从下到上一一回代即可。

无解的情况:

设消元后矩阵的秩为 rr,变量个数为 nn。

在化简为行阶梯形后,我们从底向上观察:

  • 无解:若存在某一行,其左边全为 00 但右边不为 00,无解。
  • 唯一解:不满足无解,且 rr 等于变量个数 nn。
  • 无穷解:不满足无解,且 rr 小于变量个数 nn(即存在自由变量)。

笼统的思路已经讲完了,在例题讲代码。

nn 元 11 次异或方程组

形如

{a1,1x1⊕a1,2x2⊕⋯⊕a1,nxn=a1,n+1a2,1x1⊕a2,2x2⊕⋯⊕a2,nxn=a2,n+1⋮an,1x1⊕an,2x2⊕⋯⊕an,nxn=an,n+1\begin{cases} a_{1,1}x_1 \oplus a_{1,2}x_2 \oplus \dots \oplus a_{1,n}x_n &= a_{1,n+1}\\ a_{2,1}x_1 \oplus a_{2,2}x_2 \oplus \dots \oplus a_{2,n}x_n &= a_{2,n+1}\\ &\vdots\\ a_{n,1}x_1 \oplus a_{n,2}x_2 \oplus \dots \oplus a_{n,n}x_n &= a_{n,n+1} \end{cases}

其中 xi,ai,j∈Nx_i,a_{i,j}\in\N。

由于 ⊕\oplus 运算按位独立且没有进位,我们可以将该自然数方程组拆解为 LL 个独立的 0/10/1 异或方程组。(通常 L={32,64}L = \{32,64\})

对于二进制的第 bitbit 位,其对应的 0/10/1 增广矩阵为:

Abit=[a1,1′a1,2′⋯a1,n′a2,1′a2,2′⋯a2,n′⋮⋮⋱⋮an,1′an,2′⋯an,n′a1,n+1′a2,n+1′⋮an,n+1′]A_{bit}= \left [ \begin{array}{c|c} \begin{matrix} a'_{1,1}&a'_{1,2}&\cdots&a'_{1,n}\\ a'_{2,1}&a'_{2,2}&\cdots&a'_{2,n}\\ \vdots&\vdots&\ddots&\vdots&\\ a'_{n,1}&a'_{n,2}&\cdots&a'_{n,n} \end{matrix}& \begin{matrix} a'_{1,n+1}\\ a'_{2,n+1}\\ \vdots\\ a'_{n,n+1} \end{matrix} \end{array} \right ]

其中 ai,j′a'_{i,j} 代表 ai,ja_{i,j} 在 bitbit 位上的值(00 或 11)。

在异或空间下,我们同样可以对矩阵进行初等行变换,这里主要有两种变换:

  1. 交换两行,解不变。
  2. 某行异或到另一行,解不变。(等价于普通方程组的“某行加减另一行”)。

优化:由于异或方程组的系数只有 00 和 11,可以利用 std::bitset 存矩阵的行从而整行异或,将单步消元的复杂度从 O(n)O(n) 优化至 O(nw)O(\frac{n}{w})(ww 通常 6464)。

于是我们针对每一个 bitbit 位的矩阵,将其化为行阶梯型矩阵:

Abit′=[1b1,2⋯b1,n01⋯b2,n⋮⋮⋱⋮00⋯1b1,n+1b2,n+1⋮bn,n+1]A'_{bit}= \left [ \begin{array}{c|c} \begin{matrix} 1&b_{1,2}&\cdots&b_{1,n}\\ 0&1&\cdots&b_{2,n}\\ \vdots&\vdots&\ddots&\vdots&\\ 0&0&\cdots&1 \end{matrix}& \begin{matrix} b_{1,n+1}\\ b_{2,n+1}\\ \vdots\\ b_{n,n+1} \end{matrix} \end{array} \right ]

由于元素只有 00 和 11,无需归一化。

解的判定:

设消元后第 bitbit 位矩阵的秩为 rbitr_{bit},变量个数为 nn。由于所有二进制位必须同时成立,总方程组的判定如下:

  • 无解:若存在任意一个 bitbit 位的矩阵,在化简后出现某一行“左边全为 00 但右边为 11”的情况,则整个自然数方程组无解。
  • 唯一解:不满足上述条件,且 ∀bit,rbit=n\forall bit, r_{bit} = n,则整个方程组有唯一解。
  • 无穷解:不满足上述条件,且至少存在一个 bitbit 满足 rbit<nr_{bit} < n,则整个方程组有无穷解。

关于总解数的计算: 设第 bitbit 位消元后的自由变量个数为 fbit=n−rbitf_{bit} = n - r_{bit}。由于每一位的自由元选择相互独立,根据乘法原理,整个自然数异或方程组的总解数为:

总解数=2∑bit=0L−1fbit\text{总解数} = 2^{\sum\limits_{bit=0}^{L-1} f_{bit}}

时间复杂度 O(L×n3w)O(L \times \frac{n^3}{w})。

nn 元 11 次同余方程组

形如:

{a1,1x1+a1,2x2+⋯+a1,nxn≡a1,n+1(modm)a2,1x1+a2,2x2+⋯+a2,nxn≡a2,n+1(modm)⋮an,1x1+an,2x2+⋯+an,nxn≡an,n+1(modm)\begin{cases} a_{1,1}x_1 + a_{1,2}x_2 + \dots + a_{1,n}x_n &\equiv a_{1,n+1}\pmod m\\ a_{2,1}x_1 + a_{2,2}x_2 + \dots + a_{2,n}x_n &\equiv a_{2,n+1}\pmod m\\ &\vdots\\ a_{n,1}x_1 + a_{n,2}x_2 + \dots + a_{n,n}x_n &\equiv a_{n,n+1}\pmod m \end{cases}

其中 m∈N+m\in\N^+,规定 xi∈[0,m−1]x_i\in[0,m-1]。

  • m=2m=2 时:即为特殊的异或方程组(此时 ai,j∈{0,1}a_{i,j}\in\{0,1\})。
  • mm 为质数时:直接对除法求模逆元即可,等价于普通高斯消元,复杂度 O(n3)O(n^3)。
  • 否则不一定存在模逆元,无法直接将主元系数化为 11。

对于一般情况,其对应的模 mm 增广矩阵为:

A=[a1,1a1,2⋯a1,na2,1a2,2⋯a2,n⋮⋮⋱⋮an,1an,2⋯an,na1,n+1a2,n+1⋮an,n+1](modm)A = \left [ \begin{array}{c|c} \begin{matrix} a_{1,1}&a_{1,2}&\cdots&a_{1,n}\\ a_{2,1}&a_{2,2}&\cdots&a_{2,n}\\ \vdots&\vdots&\ddots&\vdots&\\ a_{n,1}&a_{n,2}&\cdots&a_{n,n} \end{matrix}& \begin{matrix} a_{1,n+1}\\ a_{2,n+1}\\ \vdots\\ a_{n,n+1} \end{matrix} \end{array} \right ] \pmod m

为了避除法,我们采用辗转相除法(类似于欧几里得)来做初等行变换。

具体的消项:

rr 为当前主元行号。列 i∈[1,n]i \in [1, n]:

  1. 常规的找主元。
  2. 枚举接下来的每一行 k∈[r+1,n]k \in [r+1, n],通过 while() 将 ak,ia_{k,i} 消为 00:
  • 计算倍数,令 t=⌊ak,i/ar,i⌋t = \lfloor a_{k, i} / a_{r, i} \rfloor。
  • 自 j=ij = i 开始,将第 kk 行元素减去第 rr 行的 tt 倍。由于涉及减法,需做防负数取模:
ak,j←((ak,j−t×ar,j(modm))+m)(modm)a_{k,j} \gets ((a_{k,j} - t \times a_{r,j} \pmod m) + m) \pmod m
  • 检查 ak,ia_{k,i} 是否已经成功消为 00。若已经为 00,则退出 while() ,继续消下一行;若不为 00,则直接交换第 kk 行与第 rr 行,利用原 ak,ia_{k,i} 作为新的除数继续循环相除。
  1. ++r。

于是我们将矩阵化为了行阶梯型矩阵。此时 r←r−1r \gets r-1 为矩阵的秩。

解的判定与回代

我们现在有秩 rr。

由于模 mm 意义下主元可能不与 mm 互质,我们无法直接归一化。因此,判定分为第一步判定与回代时第二步判定。

1. 第一步判定(消元刚结束)

检查全 00 行的常数项:

  • 无解:若存在任意一行 k∈[r+1,n]k \in [r+1, n],左侧为 00,右侧 ak,n+1≢0(modm)a_{k, n+1} \not\equiv 0 \pmod m,则整个方程组无解。
2. 回代与第二步判定(自底向上)

第一步判定后,我们进行回代求特解或进行第二步判定。 (令 p[k] 为第 kk 行的主元所在列号,用 has_p[i] 记录第 ii 列是否存在主元)

  • 自由变量(has_p[i] == 0) 遍历 i∈[1,n]i \in [1, n],若该列不存在主元,则 xix_i 为自由变量,在模 mm 意义下有 mm 种取值方案。构造特解直接令:
xi=0x_i = 0
  • 非自由变量(自底向上遍历行,从 k=rk = r 到 k=1k = 1) 对于第 kk 行,令主元所在列为 i=p[k]i = p[k]。 将已求出的 xj (j>i)x_j \, (j > i) 代入第 kk 行方程,移项、取模,将方程变为为关于 xix_i 的一元线性同余方程:
ak,ixi≡bi′(modm)a_{k,i}x_i \equiv b'_i \pmod m

其中 bi′=((ak,n+1−∑j=i+1nak,jxj(modm))(modm)+m)(modm)b'_i = \left( \left( a_{k,n+1} - \sum\limits_{j=i+1}^n a_{k,j}x_j \pmod m \right) \pmod m + m \right) \pmod m。 令 g=gcd⁡(ak,i,m)g = \gcd(a_{k,i}, m),利用扩展欧几里得做第二步判定:

  1. 判定:若 bi′ mod g≠0b'_i \bmod g \neq 0,整个方程组无解,直接停掉。
  2. 特解:若 g∣bi′g \mid b'_i,则得到 ak,ix+my=ga_{k,i}x + my = g 的一组解 x0x_0,于是得到原方程在 [0,m−1][0, m-1] 范围内的一个特解:
xi=(x0×bi′g(modm)+m)(modm)x_i = \left( x_0 \times \frac{b'_i}{g} \pmod m + m \right) \pmod m
解的形态与总解数

在确保方程组有解的前提下,整个方程组在模 mm 意义下的解的形态由自由元和主元决定:

  • 唯一解:秩 r=nr = n(不存在自由变量),且所有主元均满足 gcd⁡(ak,p[k],m)=1\gcd(a_{k,p[k]}, m) = 1(此时各行方程的 g=1g=1,利用扩欧回代出唯一特解)。
  • 无穷解/多解:秩 r<nr < n(存在 n−rn - r 个完全自由变量);或者虽然 r=nr = n,但至少存在一个主元满足 gcd⁡(ak,p[k],m)>1\gcd(a_{k,p[k]}, m) > 1。

总解数:

自底向上考虑:

  1. 每个自由变量在模 mm 意义下可以任取 [0,m−1][0, m-1] ,方案数为 mm。
  2. 每个非自由变量对应的同余方程 ak,ixi≡bi′(modm)a_{k,i}x_i \equiv b'_i \pmod m 在有解时,其在 [0,m−1][0, m-1] 内的解数恰好为 gcd⁡(ak,i,m)\gcd(a_{k,i}, m)(各个解之间相差步长 d=mgd = \frac{m}{g})。

因此,整个同余方程组的总解数为:

mn−r×∏k=1rgcd⁡(ak,p[k],m)m^{n-r} \times \prod_{k=1}^r \gcd(a_{k,p[k]}, m)

时间复杂度 O(n3log⁡m)O(n^3 \log m)。

C++
#include<iostream>
#include<cstdio>
#include<cmath>
#define re register
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define db double
#define fi const int&
#define fl const ll&
#define ful const ull&
#define fc const char&
#define fs const string&
#define debug() puts("I Love Hina Forever")
using namespace std ;
namespace IO {
	template<class T>inline void read(T &x){char c=getchar(),f=false;x=0;while(c<48||c>57) {f|=(c==45),c=getchar();}while(c>=48&&c<=57){x=(x<<3)+(x<<1)+(c^48),c=getchar();}if(f){x=~x+1;}}
	template<class T,class ...Arg>inline void read(T &x,Arg &...arg){read(x),read(arg...);}
	template<class T>inline void write(T x){if(x<0){putchar(45),x=~x+1;}if(x>9){write(x/10);}putchar(x%10|48);}
	template<class T>inline void write(T x,fc c){write(x),putchar(c);}
}using namespace IO ;

const int N = 602,MOD = 998244353 ;
int n,m,r = 1 ;
int p[N] ;
bool has_p[N] ;
ll a[N][N],ans[N],cnt = 1 ;

inline ll exgcd (ll a,ll b,ll &x,ll &y) {
	if (!b) {
		x = 1,y = 0 ;
		return a ;
	}
	re ll g = exgcd(b,a % b,y,x) ;
	y -= a / b * x ;
	return g ;
}

inline void gauss () {
	for (re int i = 1 ; i <= n ; ++i) {
		int mx = r ;
		for (re int k = r ; k <= n ; ++k) {
			if (a[k][i] > a[mx][i]) mx = k ;
		}
		if (!a[mx][i]) continue ;
		swap(a[mx],a[r]) ;
		p[r] = i ;
		has_p[i] = 1 ;
		for (re int k = r + 1 ; k <= n ; ++k) {
			while (a[k][i]) {
				re ll t = a[k][i] / a[r][i] ;
				for (re int j = i ; j <= n + 1 ; ++j) {
					a[k][j] = ((a[k][j] - t * a[r][j] % m) % m + m) % m ;
				}
				if (!a[k][i]) break ;
				swap(a[k],a[r]) ;
			}
		}
		++r ;
	}
	--r ;
	for (re int i = r + 1 ; i <= n ; ++i) {
		if (a[i][n + 1]) {
			puts("No Solution") ;
			return ;
		}
	}
	for (re int i = 1 ; i <= n ; ++i) {
		if (!has_p[i]) {
			ans[i] = 0 ;
			cnt = cnt * m % MOD ;
		}
	}
	for (re int k = r ; k >= 1 ; --k) {
		int col = p[k] ;
		ll b1 = a[k][n + 1] ;
		for (re int j = col + 1 ; j <= n ; ++j) {
			b1 = ((b1 - a[k][j] * ans[j] % m) % m + m) % m ;
		}
		ll x0,y0 ;
		ll g = exgcd(a[k][col],m,x0,y0) ;
		if (b1 % g != 0) {
			puts("No Solution") ;
			return ;
		}
		x0 = (x0 % m + m) % m ;
		ans[col] = (x0 * (b1 / g) % m + m) % m ;
		cnt = cnt * g % MOD ;
	}
	for (re int i = 1 ; i <= n ; ++i) write(ans[i],i < n ? ' ' : endl) ;
	write(cnt,endl) ;
}
int main () {
	read(n,m) ;
	for (re int i = 1 ; i <= n ; ++i) {
		for (re int j = 1 ; j <= n + 1 ; ++j) {
			read(a[i][j]) ;
			a[i][j] = (a[i][j] % m + m) % m ;
		}
	}
	gauss() ;
	return 0 ;
}

矩阵求逆

默认模大质数 PP。

1. 矩阵求逆的方法

高斯消元。构造一个大小为 n×2nn \times 2n 的扩展增广矩阵:左半部分为原矩阵 AA,右半部分初始化为一个 n×nn \times n 的单位矩阵 II。

Aext=[A | I]=[a1,1a1,2⋯a1,n10⋯0a2,1a2,2⋯a2,n01⋯0⋮⋮⋱⋮⋮⋮⋱⋮an,1an,2⋯an,n00⋯1](modP)A_{ext} = \left [ A \ \middle| \ I \right ] = \left [ \begin{array}{cccc|cccc} a_{1,1} & a_{1,2} & \cdots & a_{1,n} & 1 & 0 & \cdots & 0 \\ a_{2,1} & a_{2,2} & \cdots & a_{2,n} & 0 & 1 & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots & \vdots \\ a_{n,1} & a_{n,2} & \cdots & a_{n,n} & 0 & 0 & \cdots & 1 \end{array} \right ] \pmod P

通过初等行变换将左半部分的 AA 彻底消成单位矩阵 II。变换结束后,右半部分对齐化出来的 [1,n][n+1,2n][1, n][n+1, 2n] 矩阵即为逆矩阵 A−1A^{-1}。

2. 具体思路

主元行 rr。

化为行阶梯型

列 i∈[1,n]i \in [1, n]:

  1. 常规找主元与交换。(若最大元为 00 则 continue 跳过本列)。交换整行时,长度需要延伸至 2n2n。用 p[r] = i 记录第 rr 行主元所在的实际列号。
  2. 归一化:直接将当前主元 ar,ia_{r,i} 归一化为 11,注意这里乘的是 ar,ia_{r,i} 的逆元。
  3. 常规消除下面,同样需要处理到 2n2n。
  4. ++r。

r←r−1r \gets r-1。若 r<nr < n,代表没有逆。

回代

由于右半部分单位矩阵的存在,这里不需要传统意义上的回代,而是直接利用已归一的主元,自底向上消除上方行的非零元。

从 k=rk = r 到第 11 行:

  1. 取第 kk 行主元所在的实际列号 col = p[k]。
  2. 枚举当前行上方所有的行 i∈[1,k−1]i \in [1, k-1],令倍数 t=ai,colt = a_{i,col}。若 t=0t = 0 则跳过。
  3. 让第 ii 行整体减去第 kk 行的 tt 倍。因为消去的是当前主元上方的元素,所以列循环只需从 col 开始向后处理到第 2n2n 列。同样做防负数取模:
ai,j←((ai,j−t×ak,j(modP))+P)(modP)a_{i,j} \gets ((a_{i,j} - t \times a_{k,j} \pmod P) + P) \pmod P

此时增广矩阵的左半部分化为单位矩阵。

右半部分 ai,j+n (i,j∈[1,n])a_{i, j+n} \, (i,j \in [1,n]) ,即为所求的逆矩阵 A−1A^{-1}。

时间复杂度 O(n3)O(n^3)。

C++
#include<iostream>
#include<cstdio>
#define re register
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define db double
#define fi const int&
#define fl const ll&
#define ful const ull&
#define fc const char&
#define fs const string&
#define debug() puts("I Love Hina Forever")
using namespace std ;
namespace IO {
	template<class T>inline void read(T &x){char c=getchar(),f=false;x=0;while(c<48||c>57) {f|=(c==45),c=getchar();}while(c>=48&&c<=57){x=(x<<3)+(x<<1)+(c^48),c=getchar();}if(f){x=~x+1;}}
	template<class T,class ...Arg>inline void read(T &x,Arg &...arg){read(x),read(arg...);}
	template<class T>inline void write(T x){if(x<0){putchar(45),x=~x+1;}if(x>9){write(x/10);}putchar(x%10|48);}
	template<class T>inline void write(T x,fc c){write(x),putchar(c);}
}using namespace IO ;
const int P = 1e9 + 7,N = 402 ;
int n,p[N],r = 1 ;
ll a[N][N << 1] ;
inline ll qpow (ll a,ll b) {
	re ll ans = 1 ;
	while (b) {
		if (b & 1) ans = ans * a % P ;
		a = a * a % P,b >>= 1 ;
	}
	return ans ;
}
inline ll inv (fl x) {return qpow(x,P - 2) ;}
inline void gauss () {
	for (re int i = 1 ; i <= n && r <= n ; ++i) {
		int mx = r ;
		for (re int k = r + 1 ; k <= n ; ++k) {
			if (a[mx][i] < a[k][i]) mx = k ;
		}
		if (!a[mx][i]) continue ;
		swap(a[r],a[mx]),p[r] = i ;
		for (re int j = n << 1 ; j >= i ; --j) (a[r][j] *= inv(a[r][i])) %= P ;
		for (re int k = r + 1 ; k <= n ; ++k) {
			int t = a[k][i] ;
			for (re int j = i ; j <= n << 1 ; ++j) {
				a[k][j] = ((a[k][j] - t * a[r][j] % P) % P + P) % P ;
			}
		}
		++r ;
	}
	--r ;
	if (r < n) {
		puts("No Solution") ;
		return ;
	}
	for (re int k = r ; k ; --k) {
		int col = p[k] ;
		for (re int i = k - 1 ; i ; --i) {
			ll t = a[i][col] ;
			if (!t) continue ;
			for (re int j = col ; j <= n << 1 ; ++j) {
				a[i][j] = ((a[i][j] - t * a[k][j] % P) % P + P) % P ;
			}
		}
	}
	for (re int i = 1 ; i <= n ; ++i) {
		for (re int j = 1 ; j <= n ; ++j) write(a[i][j + n],j < n ? ' ' : endl) ;
	}
}
int main () {
	read(n) ;
	for (re int i = 1 ; i <= n ; ++i) {
		for (re int j = 1 ; j <= n ; ++j) read(a[i][j]) ;
		a[i][i + n] = 1 ;
	}
	gauss() ;
	return 0 ;
}

行列式求值

这里的 P∈N+P \in \N ^+。

对于一个 n×nn \times n 的方阵 AA,其行列式记为 det⁡(A)\det(A)。

1. 行列式求值的方法

根据行列式的初等变换性质:

  • 若行列式 ∣T∣|T| 可以写成 ∣ABCD∣\begin{vmatrix}A&B\\C&D\end{vmatrix}(其中 A,DA,D 为方阵,BB 或 CC 为全 00 矩阵),那么 ∣T∣=∣A∣×∣D∣|T|=|A|\times|D|。
  • 交换矩阵的两行,行列式的值取反。若记某次变换为 A→ri↔rjA′A \xrightarrow{r_i \leftrightarrow r_j} A',则 det⁡(A′)=−det⁡(A)\det(A') = -\det(A)。
  • 将矩阵某行的 kk 倍加到另一行,行列式的值不变。即 A→ri←ri+k⋅rjA′A \xrightarrow{r_i \gets r_i + k \cdot r_j} A',则 det⁡(A′)=det⁡(A)\det(A') = \det(A)。
  • 将矩阵某行乘 kk,行列式的值也乘 kk。A→ri←k×riA′A \xrightarrow{r_i \gets k\times r_i} A',则 det⁡(A′)=k×det⁡(A)\det(A') = k\times\det(A)。

通过初等行变换将原方阵 AA 彻底消元为上三角矩阵 UU:

U=[u1,1u1,2⋯u1,n0u2,2⋯u2,n⋮⋮⋱⋮00⋯un,n](modP)U = \begin{bmatrix} u_{1,1} & u_{1,2} & \cdots & u_{1,n} \\ 0 & u_{2,2} & \cdots & u_{2,n} \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & u_{n,n} \end{bmatrix} \pmod P

根据上三角矩阵的行列式性质,其值等于主对角线元素的乘积。

记消元过程中产生的总行交换次数 ff,得:

det⁡(A)≡(−1)f×∏i=1nui,i(modP)\det(A) \equiv (-1)^{f} \times \prod_{i=1}^{n} u_{i,i} \pmod P
2. 消元

记 f∈{0,1}f \in \{0, 1\}(初始 f=0f = 0)维护符号。
令当前待处理的主元行指针为 rr,初始 r=1r = 1。外层循环枚举列 i∈[1,n]i \in [1, n]:

选主元与初始交换

常规选 mxmx:

  • 若 amx,i=0a_{mx,i} = 0,说明该列在阶梯面及以下元素全为 00,直接跳过该列(rr 保持不变)。
  • 若 mx≠rmx \neq r,执行行交换 rmx↔rrr_{mx} \leftrightarrow r_r,同时符号状态发生跃迁:
f←f⊕1f \gets f \oplus 1
辗转相除

对于任意行 k∈[r+1,n]k \in [r+1, n],当 ak,i≠0a_{k,i} \neq 0 时,通过以下代数迭代将其消为 00:

  1. 计算商数与倍减:
t=⌊ak,iar,i⌋t = \left\lfloor \frac{a_{k,i}}{a_{r,i}} \right\rfloor rk←(rk−t⋅rr) mod Pr_k \gets (r_k - t \cdot r_r) \bmod P
  1. 余数判定与动态交换: 若完成倍减后 ak,i=0a_{k,i} = 0,则当前行消元结束; 若 ak,i≠0a_{k,i} \neq 0,则必须再次执行行交换 rk↔rrr_k \leftrightarrow r_r,利用余数作为新的除数继续迭代。符号状态再次取反:
f←f⊕1f \gets f \oplus 1

重复上述迭代直至 ak,i=0a_{k,i} = 0。当前列消元结束后,主元行号自增:r←r+1r \gets r + 1。

3. 最终值与符号

消元结束后,秩 r←r−1r \gets r - 1。

  • 若 r<nr < n:说明消元后上三角矩阵的对角线上至少存在一个 ui,i=0u_{i,i} = 0,矩阵不满秩,其行列式的值直接为:
det⁡(A)≡0(modP)\det(A) \equiv 0 \pmod P
  • 若 r=nr = n:说明矩阵满秩,设绝对值 ansans:
ans=(∏i=1nai,i) mod Pans = \left( \prod_{i=1}^{n} a_{i,i} \right) \bmod P

最终的行列式值为:

det⁡(A)={ans,f=0(P−ans) mod P,f=1\det(A) = \begin{cases} ans, & f = 0 \\ (P - ans) \bmod P, & f = 1 \end{cases}

时间复杂度 O(n3log⁡P)O(n^3 \log P)。

代码:

C++
#include<iostream>
#include<cstdio>
#define re register
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define db double
#define fi const int&
#define fl const ll&
#define ful const ull&
#define fc const char&
#define fs const string&
#define debug() puts("I Love Hina Forever")
using namespace std ;
namespace IO {
	template<class T>inline void read(T &x){char c=getchar(),f=false;x=0;while(c<48||c>57) {f|=(c==45),c=getchar();}while(c>=48&&c<=57){x=(x<<3)+(x<<1)+(c^48),c=getchar();}if(f){x=~x+1;}}
	template<class T,class ...Arg>inline void read(T &x,Arg &...arg){read(x),read(arg...);}
	template<class T>inline void write(T x){if(x<0){putchar(45),x=~x+1;}if(x>9){write(x/10);}putchar(x%10|48);}
	template<class T>inline void write(T x,fc c){write(x),putchar(c);}
}using namespace IO ;
const int N = 602 ;
int n,m,r = 1 ;
ll a[N][N],ans = 1 ;
bool f ;
inline void gauss (const int P) {
	for (re int i = 1 ; i <= n ; ++i) {
		int mx = r ;
		for (re int k = r ; k <= n ; ++k) {
			if (a[mx][i] < a[k][i]) mx = k ;
		}
		if (!a[mx][i]) continue ;
		if (mx != r) swap(a[mx],a[r]),f ^= 1 ;
		for (re int k = r + 1 ; k <= n ; ++k) {
			while (1) {
				re ll t = a[k][i] / a[r][i] ;
				for (re int j = i ; j <= n ; ++j) {
					(((a[k][j] -= t * a[r][j] % P) %= P) += P) %= P ;
				}
				if (!a[k][i]) break ;
				swap(a[k],a[r]),f ^= 1 ;
			}
		}
		++r ;
	}
	--r ;
	if (r < n) {
		write(0) ;
		return ;
	}
	for (re int i = 1 ; i <= n ; ++i) (ans *= a[i][i]) %= P ;
	write(f ? ((-ans % P) + P) % P : ans % P) ;
}
int main () {
	read(n,m) ;
	const int P = m ;
	for (re int i = 1 ; i <= n ; ++i) {
		for (re int j = 1 ; j <= n ; ++j) read(a[i][j]),a[i][j] %= P ;
	}
	gauss(P) ;
	return 0 ;
}

例题

1. MarsOJ P2638. 高斯消元法

这就是模板题(弱化版)了。

弱化的意义是无解与无穷解统一输出 No Solution。

所以说我们在判断时只有看若有一列(j∈[1,n]j\in[1,n])全为 00 即可。

先贴代码(仅 gauss() 部分):

C++
const int N = 105 ;
const db eps = 1e-7 ;
int n ;
db a[N][N] ;
inline void gauss () {
	//Part1:
	for (re int i = 1 ; i <= n ; ++i) {
		//Step1:
		if (fabs(a[i][i]) < eps) {
			for (re int k = i + 1 ; k <= n ; ++k) {
				if (fabs(a[k][i]) > eps) {
					swap(a[k],a[i]) ;
					break ;
				}
			}
		}
		if (fabs(a[i][i]) < eps) {
			printf("No Solution") ;
			return ;
		}
		//Step2:
		for (re int j = n + 1 ; j >= i ; --j) a[i][j] /= a[i][i] ;
		//Step3:
		for (re int k = i + 1 ; k <= n ; ++k) {
			for (re int j = n + 1 ; j >= i ; --j) {
				a[k][j] -= a[i][j] * a[k][i] ;
			}
		}
	}
	//Part2:
	for (re int j = n ; j >= 2 ; --j) {
		for (re int i = j - 1 ; i ; --i) {
			a[i][n + 1] -= a[j][n + 1] * a[i][j] ;
		}
	}
	//Part3:
	for (re int i = 1 ; i <= n ; ++i) printf("%.2lf\n",a[i][n + 1]) ;
}

Part1(消元):

我们从每一列枚举(相当于枚举每个未知数 xix_i)。

目标是将 AA 削成主对角线为 11 的上三角矩阵。

Step1(找对角线不为 00 的元素):
C++
if (fabs(a[i][i]) < eps) {
	for (re int k = i + 1 ; k <= n ; ++k) {
		if (fabs(a[k][i]) > eps) {
			swap(a[k],a[i]) ;
			break ;
		}
	}
}

从 ai,ia_{i,i} 开始往下 ai+1,i,ai+2,i…a_{i+1,i},a_{i+2,i}\dots 找,直到 ak,i≠0a_{k,i}\not=0(k∈[i,n]k\in[i,n],若 ai,i≠0a_{i,i}\not=0 就不用枚了)后,将第 ii 行与第 kk 行交换。

C++
if (fabs(a[i][i]) < eps) {
    printf("No Solution") ;
    return ;
}

有一列全部为 00 就没有唯一解。

Step2(把对角线的元素削成 11):
C++
for (re int j = n + 1 ; j >= i ; --j) a[i][j] /= a[i][i] ;

就是把这一个方程都除以 ai,ia_{i,i},然后就是注意倒着枚举。

Step3(把 ai+1,i⋯an,ia_{i+1,i} \cdots a_{n,i} 削成 00):
C++
for (re int k = i + 1 ; k <= n ; ++k) {
	for (re int j = n + 1 ; j >= i ; --j) {
		a[k][j] -= a[i][j] * a[k][i] ;
	}
}

就是把第 kk 行减去(第 ii 行 ×ak,i\times a_{k,i}),目的是将 ak,ia_{k,i} 削成 00(ak,i←ak,i−1×ak,ia_{k,i} \gets a_{k,i} - 1 \times a_{k,i})(ai,ia_{i,i} 是 11)。

注意 ak,ia_{k,i} 最后变化。

Part2(回代):

C++
for (re int j = n ; j >= 2 ; --j) {
	for (re int i = j - 1 ; i ; --i) {
		a[i][n + 1] -= a[j][n + 1] * a[i][j] ;
	}
}

这时候 A←A′A \gets A'。

这时候 xn=bn,n+1x_n = b_{n,n + 1}(bn,n=1b_{n,n} = 1)。相当于我们算完了第 nn 行方程。

我们将 xnx_n 回代到上面 n−1n-1 个方程。

bi,n+1←bi,n+1−xn×bi,n,i∈[1,n−1]b_{i,n+1}\gets b_{i,n+1} - x_n \times b_{i,n},i\in[1,n-1],我们发现处理完后 xn−1x_{n-1} 又算出来了。

之后将 xn−1x_{n-1} 带入上面 n−2n-2 个方程,以此类推。

Part3:

xix_i 的答案在 bi,n+1b_{i,n+1},输出不说了。

2. MarsOJ P2641. Painter’s Problem

神仙题。

多测。

令黄色为 00,白色为 11。

每次操作格子 (i,j)(i,j) 相当于 (i,j),(i−1,j),(i+1,j),(i,j−1),(i,j+1)(i,j),(i-1,j),(i+1,j),(i,j-1),(i,j+1) 五个格子取反。
所以一个格子操作两次没有意义。

令 xi,jx_{i,j} 表示是否操作格子 (i,j)(i,j)。

所有格子的最终颜色全部变为黄色(即全为 00),那么

xi,j⊕xi−1,j⊕xi,j−1⊕xi+1,j⊕xi,j+1⊕coli,j=0xi,j⊕xi−1,j⊕xi,j−1⊕xi+1,j⊕xi,j+1=coli,j(i,j∈[1,n],xi,j,coli,j∈{0,1})\begin{aligned} x_{i,j} \oplus x_{i - 1,j} \oplus x_{i,j - 1} \oplus x_{i + 1,j} \oplus x_{i,j + 1} \oplus col_{i,j}&= 0\\ x_{i,j} \oplus x_{i - 1,j} \oplus x_{i,j - 1} \oplus x_{i + 1,j} \oplus x_{i,j + 1} &= col_{i,j} \end{aligned} \\(i,j\in[1,n],x_{i,j},col_{i,j}\in\{0,1\})

越界的下标是不合法的,直接为 00。

我们要把这 n2n^2 个方程组转化为增广矩阵。

因为一共有 n2n^2 个未知数,所以有 n2n^2 列,每一行为 xi,jx_{i,j} 的方程,故有 n2n^2 行。

{k1,1,1,1x1,1⊕k1,1,1,2x1,2⊕⋯⊕k1,1,n,n−1xn,n−1⊕k1,1,n,nxn,n=col1,1k1,2,1,1x1,1⊕k1,2,1,2x1,2⊕⋯⊕k1,2,n,n−1xn,n−1⊕k1,2,n,nxn,n=col1,2⋮kn,n−1,1,1x1,1⊕kn,n−1,1,2x1,2⊕⋯⊕kn,n−1,n,n−1xn,n−1⊕kn,n−1,n,nxn,n=coln,n−1kn,n,1,1x1,1⊕kn,n,1,2x1,2⊕⋯⊕kn,n,n,n−1xn,n−1⊕kn,n,n,nxn,n=coln,n\begin{cases} k_{1,1,1,1}x_{1,1} \oplus k_{1,1,1,2}x_{1,2} \oplus \cdots \oplus k_{1,1,n,n-1}x_{n,n-1} \oplus k_{1,1,n,n}x_{n,n} &= col_{1,1}\\ k_{1,2,1,1}x_{1,1} \oplus k_{1,2,1,2}x_{1,2} \oplus \cdots \oplus k_{1,2,n,n-1}x_{n,n-1} \oplus k_{1,2,n,n}x_{n,n} &= col_{1,2}\\ &\vdots\\ k_{n,n-1,1,1}x_{1,1} \oplus k_{n,n-1,1,2}x_{1,2} \oplus \cdots \oplus k_{n,n-1,n,n-1}x_{n,n-1} \oplus k_{n,n-1,n,n}x_{n,n} &= col_{n,n-1}\\ k_{n,n,1,1}x_{1,1} \oplus k_{n,n,1,2}x_{1,2} \oplus \cdots \oplus k_{n,n,n,n-1}x_{n,n-1} \oplus k_{n,n,n,n}x_{n,n} &= col_{n,n}\\ \end{cases}

其中 xi,j,coli,j,ki,j,k,l∈{0,1}x_{i,j},col_{i,j},k_{i,j,k,l}\in\{0,1\},

ki,j,k,l={1,(k,l)∈{(i,j),(i−1,j),(i+1,j),(i,j−1),(i,j+1)}0,otherwise⁡k_{i,j,k,l} = \begin{cases} 1,&(k,l)\in\{(i,j),(i-1,j),(i+1,j),(i,j-1),(i,j+1)\}\\ 0,&\operatorname{otherwise} \end{cases}

也就是说每一行最多有 55 个系数不为0,最少 33 个。

这样我们转化为了 n2n^2 行 n2+1n^2 + 1 列的增广矩阵。

对其进行高消。

高消后有三种情况:

  1. r<n2r<n^2 且无解,直接 inf。
  2. r=n2r = n^2,有唯一解,直接回代就行。
  3. r<n2r < n^2 但是无数解的情况,我们就直接考虑 dfs() 枚举第一行 x1,1⋯x1,nx_{1,1}\cdots x_{1,n} 的取值,进而得出第二行,第三行,……第 nn 行。

我们着重讲一下情况 3。

推导式(第 i∈[1,n)i\in[1,n) 行推第 i+1i+1 行):

xi+1,j=xi,j⊕xi−1,j⊕xi,j−1⊕xi,j+1⊕coli,jx_{i + 1,j} = x_{i,j} \oplus x_{i - 1,j} \oplus x_{i,j - 1} \oplus x_{i,j + 1} \oplus col_{i,j}

求出第 nn 行后需要看第 nn 行(前面相邻两行会相互制约,但第 nn 行没有第 n+1n+1 行进行扭转纠正)最终颜色是否全 00,合法就统计 xi,j=1x_{i,j} = 1 的数量。统计最小值。

C++
#include<iostream>
#include<cstdio>
#include<bitset>
#include<cstring>
#define re register
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define db double
#define fi const int&
#define fl const ll&
#define ful const ull&
#define fc const char&
#define fs const string&
#define debug() puts("I Love Hina Forever")
using namespace std ;
namespace IO {
	template<class T>inline void read(T &x){char c=getchar(),f=false;x=0;while(c<48||c>57) {f|=(c==45),c=getchar();}while(c>=48&&c<=57){x=(x<<3)+(x<<1)+(c^48),c=getchar();}if(f){x=~x+1;}}
	template<class T,class ...Arg>inline void read(T &x,Arg &...arg){read(x),read(arg...);}
	template<class T>inline void write(T x){if(x<0){putchar(45),x=~x+1;}if(x>9){write(x/10);}putchar(x%10|48);}
	template<class T>inline void write(T x,fc c){write(x),putchar(c);}
}using namespace IO ;
const int N = 18 ;
int T,n ;
int p[N * N],minn = 1e9 ;
bool col[N][N],x[N * N] ;
bitset<N * N> a[N * N] ;
inline void dfs (fi pos) {
	if (pos > n) {
		for (re int i = 1 ; i < n ; ++i) {
			for (re int j = 1 ; j <= n ; ++j) {
				x[n * i + j] = col[i][j] ^
							   x[n * (i - 1) + j] ^
							   (i - 2 >= 0 ? x[n * (i - 2) + j] : 0) ^
							   (j - 1 > 0 ? x[n * (i - 1) + j - 1] : 0) ^
							   (j + 1 <= n ? x[n * (i - 1) + j + 1] : 0) ;
			}
		}
		bool flg = 1 ;
		for (re int j = 1 ; j <= n ; ++j) {
			if ((x[n * (n - 1) + j] ^
				 x[n * (n - 2) + j] ^
				 (j - 1 > 0 ? x[n * (n - 1) + j - 1] : 0) ^
				 (j + 1 <= n ? x[n * (n - 1) + j + 1] : 0)) != col[n][j]) {
				flg = 0 ;
				break ;
			}
		}
		if (!flg) return ;
		int ans = 0 ;
		for (re int i = 1 ; i <= n * n ; ++i) ans += x[i] ;
		minn = min(minn,ans) ;
		return ;
	}
	x[pos] = 0,dfs(pos + 1) ;
	x[pos] = 1,dfs(pos + 1) ;
}
inline void gauss () {
	int r = 1,ans = 0 ;
	for (re int i = 1 ; i <= n * n && r <= n * n ; ++i) {
		int mx = r ;
		for (re int k = r ; k <= n * n ; ++k) {
			if (a[k][i]) {
				mx = k ;
				break ;
			}
		}
		if (!a[mx][i]) continue ;
		swap(a[mx],a[r]),p[r] = i ;
		for (re int k = r + 1 ; k <= n * n ; ++k) {
			if (a[k][i]) a[k] ^= a[r] ;
		}
		++r ;
	}
	--r ;
	for (re int i = r + 1 ; i <= n * n ; ++i) {
		if (a[i][n * n + 1]) {
			puts("inf") ;
			return ;
		}
	}
	if (r == n * n) {
		for (re int k = r,col ; k >= 1 ; --k) {
			col = p[k],x[col] = a[k][n * n + 1] ;
			for (re int j = col + 1 ; j <= n * n ; ++j) x[col] ^= a[k][j] & x[j] ;
		}
		for (re int i = 1 ; i <= n * n ; ++i) ans += x[i] ;
		write(ans,endl) ;
	}
	else {
		dfs(1) ;
		write(minn,endl) ;
	}
}
int main () {
	read(T) ;
	while (T--) {
		read(n) ;
		minn = 1e9 ;
		for (re int i = 1 ; i <= n ; ++i) {
			for (re int j = 1 ; j <= n ; ++j) {
				char c ;
				cin >> c ;
				if (c == 'y') col[i][j] = 0 ;
				else col[i][j] = 1 ;
			}
		}
		for (re int i = 1 ; i <= n ; ++i) {
			for (re int j = 1 ; j <= n ; ++j) {
				a[n * (i - 1) + j][n * n + 1] = col[i][j] ;
				a[n * (i - 1) + j][n * (i - 1) + j] = 1 ;
				if (i - 1 >= 1) a[n * (i - 1) + j][n * (i - 2) + j] = 1 ;
				if (j - 1 >= 1) a[n * (i - 1) + j][n * (i - 1) + j - 1] = 1 ;
				if (i + 1 <= n) a[n * (i - 1) + j][n * i + j] = 1 ;
				if (j + 1 <= n) a[n * (i - 1) + j][n * (i - 1) + j + 1] = 1 ;
			}
		}
		gauss() ;
		for (re int i = 1 ; i <= n * n ; ++i) a[i].reset() ;
		memset(p,0,sizeof p),memset(x,0,sizeof x) ;
	}
	return 0 ;
}

3. Luogu P2455. [SDOI2006] 线性方程组

标准的模板。

C++
const int N = 102 ;
const db eps = 1e-7 ;
int n ;
db a[N][N] ;
void Gauss () {
    int r = 1, p[N] = {0} ;
    for (re int i = 1 ; i <= n && r <= n ; ++i) {
        int mx = r ;
        for (re int k = r + 1 ; k <= n ; ++k) {
            if (fabs(a[k][i]) > fabs(a[mx][i])) mx = k ;
        }
        if (fabs(a[mx][i]) < eps) continue ;
        swap(a[r], a[mx]) ;
        for (re int j = n + 1 ; j >= i ; --j) a[r][j] /= a[r][i] ;
        p[r] = i ;
        for (re int k = r + 1 ; k <= n ; ++k) {
            db t = a[k][i] ;
            for (re int j = i ; j <= n + 1 ; ++j) {
                a[k][j] -= t * a[r][j] ;
            }
        }
        ++r ;
    }
    --r ;
    for (re int i = r + 1 ; i <= n ; ++i) {
        if (fabs(a[i][n+1]) > eps) {
            puts("-1") ;
            return ;
        }
    }
    if (r < n) {puts("0") ;return ;}
    db x[N] = {0} ;
    for (re int k = r ; k >= 1 ; --k) {
        int col = p[k] ;
        x[col] = a[k][n+1] ;
        for (re int j = col + 1 ; j <= n ; ++j) {
            x[col] -= a[k][j] * x[j] ;
        }
    }
    for (re int i = 1 ; i <= n ; ++i) {
        printf("x%d=%.2lf\n", i, x[i]) ;
    }
}

Part1(消元):

我们用 ii 枚举每一列,代表我们正在消去 xix_i;
用 rr 表示当前待处理的行下标,表示当前我们正在确定第 rr 个方程的主行。

求完后的 rr 同样表示有效的方程个数。

C++
int mx = r ;
for (re int k = r + 1 ; k <= n ; ++k) {
    if (fabs(a[k][i]) > fabs(a[mx][i])) mx = k ;
}
if (fabs(a[mx][i]) < eps) continue ;
swap(a[r],a[mx]) ;

mxmx 为在当前列寻找绝对值最大的数所在的行,把它和第 rr 行做交换。

若这一列都是 00(也就是代码里找不到),跳过这一个未知数。

C++
for (re int j = n + 1 ; j >= i ; --j) a[r][j] /= a[r][i] ;

这一行在把主元 ar,ia_{r,i} 削成 11。

相当于 ar←ar/ar,ia_r \gets a_r / a_{r,i}。

C++
p[r] = i ;

这个 pp 数组在记录每个主元的位置:第 rr 行主元为 xix_i。

C++
for (re int k = r + 1 ; k <= n ; ++k) {
    db t = a[k][i] ;
    for (re int j = i ; j <= n + 1 ; ++j) {
        a[k][j] -= t * a[r][j] ;
    }
}
r++ ;

我们在处理第 rr 行时,要把 r+1⋯nr+1 \cdots n 的 xix_i 的系数都变成 00。

相当于将第 k,k∈[r+1,n]k,k\in[r+1,n] 行方程减去了(第 rr 行方程 ×ak,i\times a_{k,i})。

即 ak(k∈[r+1,n])←ak−ak,i×ara_k(k\in[r + 1,n]) \gets a_k - a_{k,i} \times a_r。

Part2(判有无唯一解):

C++
--r ;
for (re int i = r + 1 ; i <= n ; ++i) {
    if (fabs(a[i][n+1]) > eps) {
        puts("-1") ;
        return ;
    }
}
if (r < n) {puts("0") ;return ;}

此时 rr 是矩阵的秩。

我们看 i∈[r+1,n]i\in [r+1,n] 的 ai,n+1a_{i,n+1} 有没有不是 00 的。

  • 有,就是某个方程的左边为 00,右边 ≠0\not=0,就是无解的。
  • 如果上述不满足,但是 r<nr<n,即未知数的个数多于有效方程的个数,就是有无数解的。
  • 否则就是有唯一解,继续下一步。

Part3(回代):

C++
db x[N] = {0} ;
for (re int k = r ; k >= 1 ; --k) {
    int col = p[k] ;
    x[col] = a[k][n+1] ;
    for (re int j = col + 1 ; j <= n ; ++j) {
        x[col] -= a[k][j] * x[j] ;
    }
}

数组 xx 顾名思义是 xix_i 的答案。

对于第 kk 行方程,主元是 xcolx_{col},因为是从下到上的,所以 xcol+1⋯xnx_{col+1}\cdots x_n 都是知道的,现在第 kk 行方程是长这样的:

1×xcol+ak,col+1xcol+1+⋯+ak,nxn=ak,n+11\times x_{col} + a_{k,col+1}x_{col+1} + \cdots + a_{k,n}x_{n}=a_{k,n+1}

xcolx_{col} 后面都是已知的,所以就直接带进去得了:

xcol=ak,n+1−∑j=col+1nak,jxjx_{col} = a_{k,n+1} - \sum_{j=col+1}^{n} a_{k,j}x_j

Part4:

C++
for (re int i = 1 ; i <= n ; ++i) {
    printf("x%d=%.2lf\n", i, x[i]) ;
}

xix_i 的值就是 x[i]x[i]。

3. Luogu P3812. 【模板】线性基

C++
const int N = 55 ;
int n,r = 1 ;
ll a[N],ans ;
inline void gauss () {
	for (re int i = 60 ; i >= 0 && r <= n ; --i) {
		int mx = r ;
		for (re int k = r + 1 ; k <= n ; ++k) {
			if ((a[k] >> i) & 1) {
				mx = k ;
				break ;
			}
		}
		if (!((a[mx] >> i) & 1)) continue ;
		swap(a[r],a[mx]) ;
		for (re int k = r + 1 ; k <= n ; ++k) {
			if ((a[k] >> i) & 1) {
				a[k] ^= a[r] ;
			}
		}
		++r ;
	}
}

Part1(消元):

我们将每个数看作一个关于二进制位的异或方程。

用 ii 从最高位向最低位枚举,代表我们正在消去第 ii 位(即消去该列的 1);
用 rr 表示当前待处理的方程下标,表示当前我们正在确定第 rr 个主方程。

求完后的 r−1r-1 同样表示有效方程的个数。

C++
int mx = r ;
for (re int k = r + 1 ; k <= n ; ++k) {
	if ((a[k] >> i) & 1) {
		mx = k ;
		break ;
	}
}
if (!((a[mx] >> i) & 1)) continue ;
swap(a[r],a[mx]) ;

mxmx 为在当前第 ii 位寻找一个第 ii 位为 1 的数所在的行,把它和第 rr 行做交换,作为该位的主方程。

若剩下的方程在这一位(这一列)都是 00,跳过这一位。

C++
for (re int k = r + 1 ; k <= n ; ++k) {
	if ((a[k] >> i) & 1) {
		a[k] ^= a[r] ;
	}
}
r++ ;

我们在确定了第 rr 个主方程后,要把 r+1⋯nr+1 \cdots n 行中第 ii 位的 1 全部消掉。

相当于将第 k,k∈[r+1,n]k,k\in[r+1,n] 个方程异或上了(第 rr 行的主方程)。

即 ak(k∈[r+1,n])←ak⊕ara_k(k\in[r + 1,n]) \gets a_k \oplus a_r。

Part2(贪心求最大值):

C++
ll ans = 0 ;
for (re int i = 1 ; i <= n ; ++i) {
	if ((ans ^ a[i]) > ans) ans ^= a[i] ;
}

数组 a 高消后,已经变成了一个“二进制上三角”的异或方程组。

由于高位 1 的价值远大于低位,我们从第 11 个方程(最高位)向第 nn 个方程(最低位)进行贪心:

  • 如果当前的答案 ans 异或上 a[i] 能够变得更大,就说明这个方程可以参与异或运算,将对应的位变为 1。
  • 否则不选。
ans←max⁡(ans,ans⊕ai)ans \gets \max(ans, ans \oplus a_i)

最后输出 ans 。

4. MarsOJ P2646. 【模板】Matrix-Tree 定理

这个是神秘行列式的应用。

内容

  1. 生成树计数(相当于边权都为 11):给定无向联通图(有向图),求其生成树(外向生成树 / 内向生成树)的个数。

    • 生成树:对于一个无向连通图,从中选出一些边保留下来,如果构成了一棵树,则称其为该无向连通图的生成树。
    • 外向树(内向树):从根指向叶子的树(从叶子指向根的树)。
  2. 定义其一个生成树 TT 的“权值”为 TT 中所有边权的乘积,求其所有不同生成树的“权值”之和(有 / 无向图)。(就是本题)

解法(直接讲第二个,第一个严格被包含)

三种情况的大致思路相同:

  1. 求出矩阵 D,AD,A。
  2. 算 K=D−AK = D - A。
  3. 设根为 rr,则去掉 KK 的第 rr 行和第 rr 列得到 K′K',算出 K′K' 的行列式。

区别在于 D,AD,A 矩阵的定义。

无向图

对于一个 nn 个点的无向图 GG,

1.

我们定义 DD 为度数矩阵:

Di,j={0,i≠j∑连着 i 的边权,i=jD_{i,j} = \begin{cases} 0,&i\not=j\\ \sum\limits_\text{连着 i 的边权},&i=j \end{cases}

特别地,当为第一种情况时,DD 的形式:

Di,j={0,i≠ji 的度数,i=jD_{i,j} = \begin{cases} 0,&i\not=j\\ \text{i 的度数},&i=j \end{cases}

定义 AA 为邻接矩阵:

Ai,j={∑连着 i 和 j 的边权,i≠j0,i=jA_{i,j} = \begin{cases} \sum\limits_\text{连着 i 和 j 的边权},&i\not=j\\ 0,&i=j \end{cases}

特别地,当为第一种情况时,AA 的形式:

Ai,j={连着 i 和 j 的边数,i≠j0,i=jA_{i,j} = \begin{cases} \text{连着 i 和 j 的边数},&i\not=j\\ 0,&i=j \end{cases}
2. 算 K=D−AK = D - A。
3.

因为无向图没有特殊指定根(哪个点当根都行),我们对 KK 随便去掉一行一列(一般是最后一行最后一列)去算 ∣K′∣|K'| 即可。(这是无向图具有的性质,随便去掉一行一列的行列式相同)

有向图
1.

对于一个 nn 个点的无向图 GG,

我们定义 DD 为度数矩阵(对于外向树统计入度矩阵 DinD_{in},对于内向树统计出度矩阵 DoutD_{out}):

对于外向树:

Dini,j={0,i≠j∑连向 i 的边权,i=jD_{in_{i,j}} = \begin{cases} 0,&i\not=j\\ \sum\limits_\text{连向 i 的边权},&i=j \end{cases}

特别地,当为第一种情况时,DD 的形式:

Dini,j={0,i≠ji 的入度,i=jD_{in_{i,j}} = \begin{cases} 0,&i\not=j\\ \text{i 的入度},&i=j \end{cases}

对于内向树:

Douti,j={0,i≠j∑从 i 出去的边权,i=jD_{out_{i,j}} = \begin{cases} 0,&i\not=j\\ \sum\limits_\text{从 i 出去的边权},&i=j \end{cases}

特别地,当为第一种情况时,DD 的形式:

Douti,j={0,i≠ji 的出度,i=jD_{out_{i,j}} = \begin{cases} 0,&i\not=j\\ \text{i 的出度},&i=j \end{cases}

相当于对于边 (x,y,z)(x,y,z),

  • 如果是外向树,则 zz 对 Dy,yD_{y,y} 有贡献(说明了 DD 是算入度的)。
  • 如果是内向树,则 zz 对 Dx,xD_{x,x} 有贡献(说明了 DD 是算出度的)。

定义 AA 为邻接矩阵(邻接矩阵就是用来表示图的,所以内向树与外向树是一样的):

Ai,j={∑ i 连向 j 的边权,i≠j0,i=jA_{i,j} = \begin{cases} \sum\limits_\text{ i 连向 j 的边权},&i\not=j\\ 0,&i=j \end{cases}

特别地,当为第一种情况时,AA 的形式:

Ai,j={ i 连向 j 的边数,i≠j0,i=jA_{i,j} = \begin{cases} \text{ i 连向 j 的边数},&i\not=j\\ 0,&i=j \end{cases}
2. 算 K=D−AK = D - A。
3.

设根为 rr,则求出 KK 去掉第 rr 行第 rr 列的 ∣K′∣|K'|。

注意:重边对计算没有影响,但要忽略自环(两个矩阵都要忽略!)

这里说一个求行列式的注意事项:

如果我们求 ∣A∣|A|,要将 AA 消成行阶梯的 A′A'。

设 ans=∣A∣,ans′=∣A′∣ans = |A|,ans' = |A'|。

如果我们将 AA 的某一行 ×k\times k 变成 A′A',那么 ansans 与 ans′ans' 的关系:

ans×k=ans′ans \times k = ans'

然而我们求的是 ansans,且我们已经通过乘对角线算出了 ans′ans',所以:

ans=ans′×1kans = ans' \times \dfrac{1}{k}

也就是说高消的时候去归一某一行,ans′ans' 乘的是某个数而非这个数的逆元(当然这是仅当模数是质数时才能用逆元直接算)。

C++
/*
_/        _/   _/_/_/_/_/_/   _/        _/         _/_/
_/        _/        _/        _/_/      _/       _/   _/
_/        _/        _/        _/  _/    _/      _/     _/
_/_/_/_/_/_/        _/        _/    _/  _/     _/       _/
_/        _/        _/        _/      _/_/     _/_/_/_/_/_/
_/        _/        _/        _/        _/    _/          _/
_/        _/   _/_/_/_/_/_/   _/        _/   _/            _/
*/
#include<iostream>
#include<cstdio>
#define re register
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define db double
#define fi const int&
#define fl const ll&
#define ful const ull&
#define fc const char&
#define fs const string&
#define debug() puts("I Love Hina Forever")
using namespace std ;
namespace IO {
	template<class T>inline void read(T &x){char c=getchar(),f=false;x=0;while(c<48||c>57) {f|=(c==45),c=getchar();}while(c>=48&&c<=57){x=(x<<3)+(x<<1)+(c^48),c=getchar();}if(f){x=~x+1;}}
	template<class T,class ...Arg>inline void read(T &x,Arg &...arg){read(x),read(arg...);}
	template<class T>inline void write(T x){if(x<0){putchar(45),x=~x+1;}if(x>9){write(x/10);}putchar(x%10|48);}
	template<class T>inline void write(T x,fc c){write(x),putchar(c);}
}using namespace IO ;
const int P = 1e9 + 7,N = 305 ;
int n,m,t ;
ll A[N][N],D[N][N] ;
#define mod(x) ((((x) %= P) += P) %= P)
inline ll qpow (ll a,ll b) {
	ll ans = 1 ;
	while (b) {
		if (b & 1) ans = ans * a % P ;
		b >>= 1,a = a * a % P ;
	}
	return ans ;
}
inline ll inv (ll x) {return qpow(x,P - 2) ;}
inline void gauss () {
	ll ans = 1 ;
	bool f = 0 ;
	int r = 1 ;
	for (re int i = 1 ; i <= n ; ++i) {
		int mx = r ;
		for (re int k = r ; k <= n ; ++k) {
			if (A[mx][i] < A[k][i]) mx = k ;
		}
		if (!A[mx][i]) continue ;
		if (mx != r) swap(A[mx],A[r]),f ^= 1 ;
		ll t = inv(A[r][i]) ;
		mod(ans *= A[r][i]) ;
		for (re int j = n ; j >= i ; --j) mod(A[r][j] *= t) ;
		for (re int k = r + 1 ; k <= n ; ++k) {
			for (re int j = n ; j >= i ; --j) mod(A[k][j] -= A[k][i] * A[r][j]) ;
		}
		++r ;
	}
	--r ;
	if (r < n) {
		write(0) ;
		return ;
	}
	for (re int i = 1 ; i <= n ; ++i) (ans *= A[i][i]) %= P ;
	write(f ? ((-ans % P) + P) % P : ans % P) ;
}
inline void solve1 () {
	for (re int i = 1,u,v,w ; i <= m ; ++i) {
		read(u,v,w) ;
		if (u == v) continue ;
		A[u][v] += w,A[v][u] += w ;
	}
	for (re int i = 1 ; i <= n ; ++i) {
		for (re int j = 1 ; j <= n ; ++j) D[i][i] += A[i][j] ;
	}
	for (re int i = 1 ; i <= n ; ++i) {
		for (re int j = 1 ; j <= n ; ++j) mod(A[i][j] = D[i][j] - A[i][j]) ;
	}
	--n ;
	gauss() ;
}
inline void solve2 () {
	for (re int i = 1,u,v,w ; i <= m ; ++i) {
		read(u,v,w) ;
		if (u == v) continue ;
		A[u][v] += w ;
	}
	for (re int i = 1 ; i <= n ; ++i) {
		for (re int j = 1 ; j <= n ; ++j) D[i][i] += A[j][i] ;
	}
	for (re int i = 1 ; i <= n ; ++i) {
		for (re int j = 1 ; j <= n ; ++j) mod(D[i][j] -= A[i][j]) ;
	}
	for (re int i = 1 ; i < n ; ++i) {
		for (re int j = 1 ; j < n ; ++j) A[i][j] = D[i + 1][j + 1] ;
	}
	--n ;
	gauss() ;
}
int main () {
	read(n,m,t) ;
	if (t == 0) solve1() ;
	else solve2() ;
	return 0 ;
}

5. MarsOJ P2733. 文艺计算姬

依旧神仙题。

题目即求解带标号完全二分图 Kn,mK_{n,m} 的生成树个数,结果对 pp 取模。

二分图:对于图 GG,若能将其点集 VV 划分为两个不相交的非空子集 AA 和 BB,使得图中的每条边所连接的两个顶点分别属于这两个不同的点集(即点集内部没有连边),则称 GG 为二分图。

完全二分图:对于二分图 GG,设其分成的两个点集为 AA 和 BB。若对于任意的 x∈Ax \in A 和 y∈By \in B,图中都存在一条边连接 xx 和 yy,则称 GG 为完全二分图(若 AA 的大小为 mm,BB 的大小为 nn,可记作 Km,nK_{m,n})。

对于“普通计算机”,求的是完全图的生成树数量:ans=nn−2ans = n^{n-2}(Cayley 公式)。

而对于我们要求的即为扩展 Cayley 公式(对于 Kn,mK_{n,m}):ans=nm−1×mn−1ans = n^{m-1} \times m^{n-1}。

这个可以用 Matrix-Tree 推导。

推导

对于 DD,其形式为:

D=[m⋱mn⋱n](n+m)×(n+m)=[m⋅InOn×mOm×nn⋅Im]D = \begin{bmatrix} m & & & & & \\ & \ddots & & & & \\ & & m & & & \\ & & & n & & \\ & & & & \ddots & \\ & & & & & n \end{bmatrix}_{(n+m) \times (n+m)} = \begin{bmatrix} m \cdot I_n & O_{n\times m} \\ O_{m\times n} & n \cdot I_m \end{bmatrix}

对于 AA,其形式为:

A=[0⋯01⋯1⋮⋱⋮⋮⋱⋮0⋯01⋯11⋯10⋯0⋮⋱⋮⋮⋱⋮1⋯10⋯0](n+m)×(n+m)=[OnJn×mJm×nOm]A = \begin{bmatrix} 0 & \cdots & 0 & 1 & \cdots & 1 \\ \vdots & \ddots & \vdots & \vdots & \ddots & \vdots \\ 0 & \cdots & 0 & 1 & \cdots & 1 \\ 1 & \cdots & 1 & 0 & \cdots & 0 \\ \vdots & \ddots & \vdots & \vdots & \ddots & \vdots \\ 1 & \cdots & 1 & 0 & \cdots & 0 \end{bmatrix}_{(n+m) \times (n+m)} = \begin{bmatrix} O_n & J_{n \times m} \\ J_{m \times n} & O_m \end{bmatrix}

那么 K=D−A=(m⋅In−Jn×m−Jm×nn⋅Im)K = D - A = \begin{pmatrix} m \cdot I_n & -J_{n \times m} \\ -J_{m \times n} & n \cdot I_m \end{pmatrix}。

我们去掉 KK 的最后一行最后一列,得到 K′K'。

∣K′∣=∣m⋅In−Jn×(m−1)−J(m−1)×nn⋅Im−1∣|K'| = \begin{vmatrix} m \cdot I_n & -J_{n \times (m-1)} \\ -J_{(m-1) \times n} & n \cdot I_{m-1} \end{vmatrix}

我们将(上面每一行相加再 ×1m\times \dfrac{1}{m})加到下面每一行上(相当于 t=∑i=1nKi′,Kj′←Kj′+tm(j∈[n+1,n+m−1])t = \sum\limits_{i=1}^nK'_i,K'_j\gets K'_j+\dfrac{t}{m}(j\in[n+1,n+m-1])),
就是利用前 nn 行,将左下角的 −J(m−1)×n-J_{(m-1) \times n} 消为 OO:

∣K′∣=∣m⋯0−1⋯−1⋮⋱⋮⋮⋱⋮0⋯m−1⋯−10⋯0n−nm⋯−nm⋮⋱⋮⋮⋱⋮0⋯0−nm⋯n−nm∣|K'| = \left| \begin{array}{ccc|ccc} m & \cdots & 0 & -1 & \cdots & -1 \\ \vdots & \ddots & \vdots & \vdots & \ddots & \vdots \\ 0 & \cdots & m & -1 & \cdots & -1 \\ \hline 0 & \cdots & 0 & n-\frac{n}{m} & \cdots & -\frac{n}{m} \\ \vdots & \ddots & \vdots & \vdots & \ddots & \vdots \\ 0 & \cdots & 0 & -\frac{n}{m} & \cdots & n-\frac{n}{m} \end{array} \right|

于是 ∣K′∣=|K'|= 左上 ×\times 右下:

∣K′∣=∣m⋅In∣×∣n−nm−nm⋯−nm−nmn−nm⋯−nm⋮⋮⋱⋮−nm−nm⋯n−nm∣(m−1)×(m−1)=mn×∣n−nm−nm⋯−nm−nmn−nm⋯−nm⋮⋮⋱⋮−nm−nm⋯n−nm∣(m−1)×(m−1)|K'| = |m \cdot I_n| \times \left| \begin{array}{cccc} n-\frac{n}{m} & -\frac{n}{m} & \cdots & -\frac{n}{m} \\ -\frac{n}{m} & n-\frac{n}{m} & \cdots & -\frac{n}{m} \\ \vdots & \vdots & \ddots & \vdots \\ -\frac{n}{m} & -\frac{n}{m} & \cdots & n-\frac{n}{m} \end{array} \right|_{(m-1) \times (m-1)} = m^n \times\left| \begin{array}{cccc} n-\frac{n}{m} & -\frac{n}{m} & \cdots & -\frac{n}{m} \\ -\frac{n}{m} & n-\frac{n}{m} & \cdots & -\frac{n}{m} \\ \vdots & \vdots & \ddots & \vdots \\ -\frac{n}{m} & -\frac{n}{m} & \cdots & n-\frac{n}{m} \end{array} \right|_{(m-1) \times (m-1)}

对于右侧那一坨我们设为 ∣T∣|T|,我们将第 22 行到第 m−1m-1 行都加到第 11 行上(t=∑i=2m−1Ti,T1←T1+tt = \sum\limits_{i=2}^{m-1}T_i,T_1\gets T_1+t):

∣T∣=∣nmnm⋯nm−nmn−nm⋯−nm⋮⋮⋱⋮−nm−nm⋯n−nm∣|T|= \begin{vmatrix} \frac{n}{m} & \frac{n}{m} & \cdots & \frac{n}{m} \\ -\frac{n}{m} & n-\frac{n}{m} & \cdots & -\frac{n}{m} \\ \vdots & \vdots & \ddots & \vdots \\ -\frac{n}{m} & -\frac{n}{m} & \cdots & n-\frac{n}{m} \end{vmatrix}

我们将第 11 行加到下面所有行上(Ti←Ti+T1(i∈[2,m−1])T_i\gets T_i+T_1(i\in[2,m-1])):

∣T∣=∣nmnm⋯nm0n⋯0⋮⋮⋱⋮00⋯n∣=nm×nm−2|T|= \begin{vmatrix} \frac{n}{m} & \frac{n}{m} & \cdots & \frac{n}{m} \\ 0 & n & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & n \end{vmatrix} = \frac{n}{m} \times n^{m-2}

那么最终,∣K′∣=mn×(nm×nm−2)=mn−1×nm−1|K'|=m^n\times(\dfrac{n}{m}\times n^{m-2})=m^{n-1}\times n^{m-1}。

注意对 pp 取模。

C++
/*
_/        _/   _/_/_/_/_/_/   _/        _/         _/_/
_/        _/        _/        _/_/      _/       _/   _/
_/        _/        _/        _/  _/    _/      _/     _/
_/_/_/_/_/_/        _/        _/    _/  _/     _/       _/
_/        _/        _/        _/      _/_/     _/_/_/_/_/_/
_/        _/        _/        _/        _/    _/          _/
_/        _/   _/_/_/_/_/_/   _/        _/   _/            _/
*/
#include<iostream>
#include<cstdio>
#define re register
#define endl '\n'
#define ll __int128
#define ull unsigned long long
#define db double
#define fi const int&
#define fl const ll&
#define ful const ull&
#define fc const char&
#define fs const string&
#define debug() puts("I Love Hina Forever")
using namespace std ;
namespace IO {
	template<class T>inline void read(T &x){char c=getchar(),f=false;x=0;while(c<48||c>57) {f|=(c==45),c=getchar();}while(c>=48&&c<=57){x=(x<<3)+(x<<1)+(c^48),c=getchar();}if(f){x=~x+1;}}
	template<class T,class ...Arg>inline void read(T &x,Arg &...arg){read(x),read(arg...);}
	template<class T>inline void write(T x){if(x<0){putchar(45),x=~x+1;}if(x>9){write(x/10);}putchar(x%10|48);}
	template<class T>inline void write(T x,fc c){write(x),putchar(c);}
}using namespace IO ;
ll n,m,p ;
inline ll qpow (ll a,ll b) {
	ll ans = 1 ;
	while (b) {
		if (b & 1) ans = ans * a % p ;
		b >>= 1,a = a * a % p ;
	}
	return ans ;
}
int main () {
	read(n,m,p) ;
	write(qpow(n,m - 1) * qpow(m,n - 1) % p) ;
	return 0 ;
}

6. MarsOJ P2649. Expectation

定义生成树的“权值”为所有边权的按位与。

求随即一颗生成树权值期望。

思路

首先总情况数即总生成树个数 sumsum。

因为按位与对于每一个二进制位来说互不干涉,我们将边权拆为每一位去看。

把图中边权第 ii 个二进制位为 11 的边提出来建一个新图(只有全 11 才有贡献)求生成树个数 nowinow_i,对应的值为 2i2^i。

期望 p=∑i=1basenowisum×2ip = \sum\limits_{i=1}^{base}\dfrac{now_i}{sum}\times 2^i。

C++
/*
_/        _/   _/_/_/_/_/_/   _/        _/         _/_/
_/        _/        _/        _/_/      _/       _/   _/
_/        _/        _/        _/  _/    _/      _/     _/
_/_/_/_/_/_/        _/        _/    _/  _/     _/       _/
_/        _/        _/        _/      _/_/     _/_/_/_/_/_/
_/        _/        _/        _/        _/    _/          _/
_/        _/   _/_/_/_/_/_/   _/        _/   _/            _/
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#define re register
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define db double
#define fi const int&
#define fl const ll&
#define ful const ull&
#define fc const char&
#define fs const string&
#define debug() puts("I Love Hina Forever")
using namespace std ;
namespace IO {
	template<class T>inline void read(T &x){char c=getchar(),f=false;x=0;while(c<48||c>57) {f|=(c==45),c=getchar();}while(c>=48&&c<=57){x=(x<<3)+(x<<1)+(c^48),c=getchar();}if(f){x=~x+1;}}
	template<class T,class ...Arg>inline void read(T &x,Arg &...arg){read(x),read(arg...);}
	template<class T>inline void write(T x){if(x<0){putchar(45),x=~x+1;}if(x>9){write(x/10);}putchar(x%10|48);}
	template<class T>inline void write(T x,fc c){write(x),putchar(c);}
}using namespace IO ;
const int N = 102,P = 998244353 ;
int T,n,m ;
ll K[N][N],sum,ans ;
struct node {
	int x,y ;
	ll z ;
}e[N * N] ;
#define mod(x) ((((x) %= P) += P) %= P)
inline ll qpow (ll a,ll b) {
	re ll ans = 1 ;
	while (b) {
		if (b & 1) ans = ans * a % P ;
		b >>= 1,a = a * a % P ; 
	}
	return ans ;
}
inline ll inv (fl x) {return qpow(x,P - 2) ;}
inline ll gauss (ll a[N][N]) {
	int r = 1 ;
	bool f = 0 ;
	ll ans = 1 ;
	for (re int i = 1 ; i <= n && r <= n ; ++i) {
		int mx = r ;
		for (re int k = r ; k <= n ; ++k) {
			if (a[k][i]) {
				mx = k ;
				break ;
			}
		}
		if (!a[mx][i]) continue ;
		if (mx != r) f ^= 1 ;
		swap(a[mx],a[r]),mod(ans *= a[r][i]) ;
		ll t = inv(a[r][i]) ;
		for (re int j = n ; j >= i ; --j) mod(a[r][j] *= t) ;
		for (re int k = r + 1 ; k <= n ; ++k) {
			for (re int j = n ; j >= i ; --j) mod(a[k][j] -= a[k][i] * a[r][j]) ;
		}
		++r ;
	}
	--r ;
	if (r < n) return 0 ;
	return f == 1 ? ((-ans % P) + P) % P : ans % P ;
}
inline void solve () {
	memset(K,0,sizeof K) ;
	for (re int i = 1,x,y,z ; i <= m ; ++i) {
		x = e[i].x,y = e[i].y,z = e[i].z ;
		++K[x][x],++K[y][y],--K[x][y],--K[y][x] ;
	}
	for (re int i = 1 ; i <= n ; ++i) {
		for (re int j = 1 ; j <= n ; ++j) mod(K[i][j]) ;
	}
	--n ;
	sum = gauss(K) ;
	if (sum == 0) {
		ans = 0 ;
		return ;
	}
	sum = inv(sum) ;
	++n ;
	for (re int bit = 0 ; bit < 30 ; ++bit) {
		memset(K,0,sizeof K) ;
		for (re int i = 1,x,y,z ; i <= m ; ++i) {
			x = e[i].x,y = e[i].y,z = e[i].z ;
			if ((z >> bit) & 1) ++K[x][x],++K[y][y],--K[x][y],--K[y][x] ;
		}
		for (re int i = 1 ; i <= n ; ++i) {
			for (re int j = 1 ; j <= n ; ++j) mod(K[i][j]) ;
		}
		--n ;
		mod(ans += gauss(K) * sum % P * (1ll << bit) % P) ;
		++n ;
	}
}
int main () {
	read(T) ;
	while (T--) {
		read(n,m) ;
		int cnt = 0 ;
		for (re int i = 1,x,y,z ; i <= m ; ++i) {
			read(x,y,z) ;
			if (x == y) continue ;
			e[++cnt] = {x,y,z} ;
		}
		m = cnt ;
		solve() ;
		write(ans,endl) ;
		ans = sum = 0 ;
	}
	return 0 ;
}