输入一个包含 𝑛 个方程 𝑛 个未知数的异或线性方程组。
方程组中的系数和常数为 0 或 1,每个未知数的取值也为 0 或 1。
求解这个方程组。
异或线性方程组示例如下:
M[1][1]x[1] ^ M[1][2]x[2] ^ … ^ M[1][n]x[n] = B[1]
M[2][1]x[1] ^ M[2][2]x[2] ^ … ^ M[2][n]x[n] = B[2]
…
M[n][1]x[1] ^ M[n][2]x[2] ^ … ^ M[n][n]x[n] = B[n]
其中 ^
表示异或(𝑋𝑂𝑅),𝑀[𝑖][𝑗] 表示第 𝑖 个式子中 𝑥[𝑗] 的系数,𝐵[𝑖] 是第 𝑖 个方程右端的常数,取值均为 0 或 1。
输入格式
第一行包含整数 𝑛。
接下来 𝑛 行,每行包含 𝑛+1 个整数 0 或 1,表示一个方程的 𝑛 个系数以及等号右侧的常数。
输出格式
如果给定线性方程组存在唯一解,则输出共 𝑛 行,其中第 𝑖 行输出第 𝑖 个未知数的解。
如果给定线性方程组存在多组解,则输出 Multiple sets of solutions
。
如果给定线性方程组无解,则输出 No solution
。
数据范围
1≤𝑛≤100
输入样例:
3
1 1 0 1
0 1 1 0
1 0 0 1
输出样例:
1
0
0
代码:
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int N = 110;
int n;
int a[N][N];
int Gauss(){
int row,col;
for(row = 0,col = 0;col < n;col ++){
int tmp = row;
for(int i = row;i < n;i ++){
if(a[i][col] > a[tmp][col]){
tmp = i;
}
}
if(a[tmp][col] == 0){
continue;
}
for(int i = col;i <= n;i ++){
swap(a[row][i],a[tmp][i]);
}
//省去化简
for(int i = row + 1;i < n;i ++){
if(a[i][col] == 1){
for(int j = col;j <= n;j ++){
a[i][j] ^= a[row][j];
}
}
}
row ++;
}
if(row < n){
for(int i = row;i < n;i ++){
if(a[i][n] == 1){
return -1;
}
}
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];
}
}
return 0;
}
int main(){
cin>>n;
for(int i = 0;i < n;i ++){
for(int j = 0;j <= n;j++){
cin>>a[i][j];
}
}
int res = Gauss();
if(res == 0){
for(int i = 0;i < n;i ++){
printf("%d\n",a[i][n]);
}
}else if(res == -1){
cout<<"No solution";
}else if(res == 1){
cout<<"Multiple sets of solutions";
}
return 0;
}