P3389 【模板】高斯消元法 题解

· · 题解

高斯消元法是一个用来求解线性方程组的算法。

可以解出形如

\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 元一次方程组。

高斯消元主要是运用两种消元方法:加减消元法和代入消元法,和初中生解一次方程组一样。

高斯消元的方法是,使用主元法,先进行加减消元,然后我们可以先求得 x_1,然后可以逐层往回代,依次可以得到 x_2,x_3\cdots x_n。

举个例子,方程

\begin{cases} x + 3y + 4z = 5 \\ x + 4y + 7z = 3 \\ 9x + 3y + 2z = 2 \end{cases}

先写进矩阵:

1 & 3 & 4 & | & 5 \\ 1 & 4 & 7 & | & 3 \\ 9 & 3 & 2 & | & 2 \end{bmatrix}

然后通过主元法,系数化为 1,上下加减,得到:

0.25 & 0.75 & 1 & | & 1.25 \\ 0.14 & 0.57 & 1 & | & 0.43 \\ 4.5 & 1.5 & 1 & | & 1 \end{bmatrix}

加减消元:

\begin{cases} 0.11x + 0.18y = 0.82 \\ -4.36x -0.57y = -0.57\end{cases}

使用相同的方法:

可得 x=3.98\times -\dfrac{1}{4.09}=0.97

但是怎么回代呢?

我们每次操作的时候留下一个当前的方程,矩阵会变成这样:

-4.09 & 1 & 1 & | & 3.98 \\ 4.69 & 1 & 1 & | & 0.62 \\ 4.5 & 1.5 & 1 & | & 1 \end{bmatrix}

回代,解得

\begin{cases} x = -0.97 \\ y = 5.18 \\ z = -2.39 \end{cases}

如果一个方程没有了系数不为 0 的项,则方程无解或者有无数解,输出 No Solution。

复杂度 \mathcal{O}(n^3),可以过。

参考代码:

#include<bits/stdc++.h>
using namespace std;
const int N = 110;
const double eps = 1e-6;
int n; double a[N][N];
bool gauss() {
    int r = 0;
    for(int c = 0; c < n; c++) {
        int t = r;
        for(int i = r; i < n; i++)
            if(fabs(a[i][c]) > fabs(a[t][c]))
                t = i;
        if(fabs(a[t][c]) < eps) continue;
        for(int i = c; i < n + 1; i++) swap(a[t][i], a[r][i]);
        for(int i = n; i >= c; i--) a[r][i] /= a[r][c];
        for(int i = r + 1; i < n; i++)
            if(fabs(a[i][c]) > eps)
                for(int j = n; j >= c; j--)
                    a[i][j] -= a[r][j] * a[i][c];
        r++;
    }
    if(r < n) return 1;
    for(int i = n - 1; i >= 0; i--) for(int j = i + 1; j < n; j++) a[i][n] -= a[j][n] * a[i][j];
    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];
    bool t = gauss();
    if(t == 0) for(int i = 0; i < n; i++) printf("%.2lf\n", a[i][n]);
    else puts("No Solution");
    return 0;
}