题目链接:传送门
高斯消元
可以去下面看一下
https://www.bilibili.com/video/av4688674 听视频比瞅博客有用得多
这题算比较标准的板子了
各种情况都有
有个好板子非常滴重要
但更重要的是弄明白原理
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <complex>
#include <algorithm>
#include <climits>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <iomanip>
#define
#define
using namespace std;
typedef long long ll;
const double epp = 1e-8;
double f[B][B], ans[B];
int n, ok1, ok2;
int main(int argc, char const *argv[]) {
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n + 1; j++)
cin >> f[i][j];
for (int i = 1; i <= n; i++) {
int pos = i;
for (int j = i + 1; j <= n; j++) if (fabs(f[j][i]) > fabs(f[pos][i])) pos = j;
for (int j = 1; j <= n + 1; j++) swap(f[pos][j], f[i][j]);
if (fabs(f[i][i]) < epp) continue;
double tf = f[i][i];
for (int j = 1; j <= n + 1; j++) f[i][j] /= tf;
for (int j = 1; j <= n; j++)
if (i != j) {
double x = f[j][i];
for (int k = 1; k <= n + 1; k++) f[j][k] -= f[i][k] * x;
}
}
for (int i = 1; i <= n; i++) {
int j = 1;
while (fabs(f[i][j]) < epp and j <= n + 1) j++;
if (j > n + 1) ok1 = 1;
else if (j == n + 1) ok2 = 1;
}
if (ok2) return puts("-1"), 0;
if (ok1) return puts("0"), 0;
for (int i = n; i >= 1; i--) {
ans[i] = f[i][n + 1];
for (int j = i - 1; j >= 1; j--) {
f[j][n + 1] -= ans[i] * f[j][i];
f[j][i] = 0;
}
}
for (int i = 1; i <= n; i++)
if (fabs(ans[i]) < epp) printf("x%d=0\n", i);
else cout << "x" << i << "=" << fixed << setprecision(2) << ans[i] << endl;
}