白书高斯消元模板
『题目链接』白书P287
✿说明✿
这个就是直接模拟解方程的过程,当有具体的可解一次方程时,就可以用这个。也注意下数据范围,100左右的时候才可用。
『时间复杂度』 O(n3)
✿CODE✿
#include <map>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <set>
#include <queue>
#include <cstring>
#include <algorithm>
using namespace std;
const double EPS = 1e-8;
typedef vector<double> vec;
typedef vector<vec> mat;
vec gauss_jordan(const mat& A, const vec& b) {
int n = A.size();
mat B(n, vec(n + 1));
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
B[i][j] = A[i][j];
for (int i = 0; i < n; i++)
B[i][n] = b[i];
for (int i = 0; i < n; i++) {
int pivot = i;
for (int j = i; j < n; j++) {
if (abs(B[j][i]) > abs(B[pivot][i])) pivot = j;
}
swap(B[i], B[pivot]);
if (abs(B[i][i]) < EPS) return vec();
for (int j = i + 1; j <= n; j++) {
B[i][j] /= B[i][i];
}
for (int j = 0; j < n; j++) {
if (i != j) {
for (int k = i + 1; k <= n; k++)
B[j][k] -= B[j][i] * B[i][k];
}
}
}
vec x(n);
for (int i = 0; i < n; i++)
x[i] = B[i][n];
return x;
}
int main() {
freopen("1.in", "r", stdin);
mat A{{1, -2, 3}, {4, -5, 6}, {7, -8, 10}};
vec B{6, 12, 21};
vec x = gauss_jordan(A, B);
if (x.size()) {
for (auto &i : x) {
cout << i << ' ';
} printf("\n");
}
else {
puts("Oops");
}
return 0;
}