「SDOI2006」线性方程组 - 高斯消元

题意描述

洛谷链接

已知 \(n\) 元线性一次方程组。

\[ \begin{cases} a_{1, 1} x_1 + a_{1, 2} x_2 + \cdots + a_{1, n} x_n = b_1 \\ a_{2, 1} x_1 + a_{2, 2} x_2 + \cdots + a_{2, n} x_n = b_2 \\ \cdots \\ a_{n,1} x_1 + a_{n, 2} x_2 + \cdots + a_{n, n} x_n = b_n \end{cases} \]

请根据输入的数据,编程输出方程组的解的情况。

解题思路

对于求 \(n\) 元一次方程组,显然需要用高斯消元。但本题需要判断无解或无穷解。对于此类,我们可以在高斯消元后判断第 \(i\) 行第 \(i\) 项是否为 \(0\)。若为 \(0\) 且最后一项不为 \(0\),无解。在判断有解的前提下,第 \(i\) 行第 \(i\) 项同时为 \(0\) 则有无穷解。

最后注意一下需要调换增广矩阵每一行的位置。对于第 \(i\) 行可将未计算的行中最大的第 \(i\) 项所在行调换。

代码演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>

const int MAXN = 100;

int n;
double a[MAXN + 1][MAXN + 2];

inline void swaps(int i, int j) {
for (int k = 1; k <= n + 1; k++) {
std::swap(a[i][k], a[j][k]);
}
}

inline void sorts(int pos) {
int maxn = pos;
for (int i = pos + 1; i <= n; i++) {
if (fabs(a[maxn][pos]) < fabs(a[i][pos])) {
maxn = i;
}
}
if (pos != maxn) swaps(pos, maxn);
}

inline void gauss() {
for (int i = 1; i <= n; i++) {
sorts(i);
if (a[i][i] == 0) continue;
for (int j = i + 1; j <= n + 1; j++) a[i][j] /= a[i][i];
a[i][i] = 1;

for (int j = i + 1; j <= n; j++) {
for (int k = i + 1; k <= n + 1; k++) {
a[j][k] -= a[i][k] * a[j][i] / a[i][i];
}
a[j][i] = 1;
}
}
}

inline int solve() {
for (int i = n; i > 1; i--) {
for (int j = 1; j < i; j++) {
a[j][n + 1] -= a[i][n + 1] * a[j][i] / a[i][i];
a[j][i] = 0;
}
}

int op = 1;
for (int i = 1; i <= n; i++) {
if (a[i][i] == 0 && a[i][n + 1] != 0) op = -1;
if (a[i][i] == 0 && a[i][n + 1] == 0 && op == 1) op = 0;
}

return op;
}

int main() {
std::cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n + 1; j++) {
scanf("%lf", &a[i][j]);
}
}

gauss();

int op = solve();

if (op != 1) std::cout << op << std::endl;
else for (int i = 1; i <= n; i++) printf("x%d=%.2lf\n", i, a[i][n + 1]);

return 0;
}