跳到正文

题解

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

sto_5k_orz约 4 分钟
原文
文章信息与版本

文章信息

发布
2023年12月8日
收录
2026年8月20日
更新
2026年10月29日
篇幅
约 4 分钟
获赞
19
题目
P3389

版本

  1. v1当前

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

可以解出形如

{a1,1x1+a1,2x2+⋯+a1,nxn=b1a2,1x1+a2,2x2+⋯+a2,nxn=b2⋯an,1x1+an,2x2+⋯+an,nxn=bn \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}

的 nn 元一次方程组。

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

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

举个例子,方程

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

先写进矩阵:

[134∣5147∣3932∣2]\begin{bmatrix} 1 & 3 & 4 & | & 5 \\ 1 & 4 & 7 & | & 3 \\ 9 & 3 & 2 & | & 2 \end{bmatrix}

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

[0.250.751∣1.250.140.571∣0.434.51.51∣1]\begin{bmatrix} 0.25 & 0.75 & 1 & | & 1.25 \\ 0.14 & 0.57 & 1 & | & 0.43 \\ 4.5 & 1.5 & 1 & | & 1 \end{bmatrix}

加减消元:

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

使用相同的方法:

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

但是怎么回代呢?

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

[−4.0911∣3.984.6911∣0.624.51.51∣1]\begin{bmatrix} -4.09 & 1 & 1 & | & 3.98 \\ 4.69 & 1 & 1 & | & 0.62 \\ 4.5 & 1.5 & 1 & | & 1 \end{bmatrix}

回代,解得

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

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

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

参考代码:

C++
#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;
}
原文
存档评论3 条抓取于