AcWing 题目
其实和高斯消元解线性方程组一样,就是加法变成了异或运算,可能会有点绕。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int N = 105;
static int a[][] = new int[N][N];
static int n;
public static int gauss() {
int row, colomn;
for (row = 0, colomn = 0; colomn < n; colomn++) {
int t = row;
for (int i = row; i < n; i++) {
if (a[i][colomn] != 0) {
t = i;
break;
}
}
if (a[t][colomn] == 0) continue;
for (int i = colomn; i <= n; i++) {
int temp = a[t][i];
a[t][i] = a[row][i];
a[row][i] = temp;
}
for (int i = row + 1; i < n; i++) {
if (a[i][colomn] != 0)
for (int j = colomn; 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;
}
public static void main(String[] args) throws IOException {
String[] s = br.readLine().split(" ");
n = Integer.parseInt(s[0]);
for (int i = 0; i < n; i++) {
s = br.readLine().split(" ");
for (int j = 0; j < n + 1; j++)
a[i][j] = Integer.parseInt(s[j]);
}
int res = gauss();
if (res == 0)
for (int i = 0; i < n; i++)
pw.println(a[i][n]);
else if (res == 1)
pw.println("Multiple sets of solutions");
else
pw.println("No solution");
pw.flush();
br.close();
}
}