高斯消元-解异或线性方程
核心
1. 理解异或线性方程为什么可以用高斯线性方程解法
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 110;
int n;
int a[N][N];
int gauss() // 高斯消元,答案存于a[i][n]中,0 <= i < n
{
int c, r;
for (c = 0, r = 0; c < n; c ++ )
{
int t = r;
for (int i = r; i < n; i ++ ) // 找非零行
if (a[i][c])
t = i;
if (!a[t][c]) continue;
for (int i = c; i <= n; i ++ ) swap(a[r][i], a[t][i]); // 将非零行换到最顶端
for (int i = r + 1; i < n; i ++ ) // 用当前行将下面所有的列消成0
if (a[i][c])
for (int j = n; j >= c; j -- )
a[i][j] ^= a[r][j];
r ++ ;
}
if (r < n)
{
for (int i = r; i < n; i ++ )
if (a[i][n])
return 2; // 无解
return 1; // 有多组解
}
for (int i = n - 1; i >= 0; i -- )
for (int j = i + 1; j < n; j ++ )
a[i][n] ^= a[i][j] * a[j][n]; // a[i][j] 是0,&之后就是0,是1则&之后为1,再^就为0
return 0; // 有唯一解
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n + 1; j++) {
cin >> a[i][j];
}
}
int t = gauss();
if (t == 0) {
for (int i = 0; i < n; i++) cout << a[i][n] << endl;
} else if (t == 1) {
cout << "Multiple sets of solutions" << endl;
} else {
cout << "No solution" << endl;
}
return 0;
}