Godzilla @ 2021-07-07 14:53:54
约旦-高斯消元法
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#define LL long long
#define DB double
using namespace std;
const int kN = 105;
const DB kEps = 1e-16;
int n, sum;
DB a[kN][kN], ans[kN];
signed main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
for (int j = 1;j <= n + 1; ++j) {
scanf("%lf", &a[i][j]);
}
}
for (int i = 1; i <= n; ++i) {
int p = i;
for (int j = i + 1; j <= n; ++j) {
if(fabs(a[j][i]) > fabs(a[p][i])) {
swap(p, j);
}
}
if(fabs(a[p][i]) < kEps) {continue;}
if (p != i) {
for (int j = i; j <= n + 1; ++j) {
swap(a[p][j], a[i][j]);
}
}
DB div = a[i][i];
for (int j = i; j <= n + 1; ++j) {
a[i][j] /= div;
}
for (int j = 1; j <= n; ++j) {
if(j != i) {
DB w = a[j][i] / a[i][i];
for (int k = i; k <= n + 1; ++k) {
a[j][k] -= a[i][k] * w;
}
}
}
sum++;
}
for (int i = 1; i <= n; ++i) {
ans[i] = a[i][n + 1];
}
if(sum < n) {
for (int i = 1; i <= n; ++i) {
if(fabs(ans[i]) < kEps && fabs(a[i][n + 1]) > kEps) {
printf("-1\n");return 0;
}
}
printf("0\n");return 0;
}
for (int i = 1; i <= n; ++i) {
printf("x%d=", i);
printf("%.2lf\n", ans[i]);
}
return 0;
}
/*
2
0 2 3
0 0 0
*/