【模板】高斯消元

· · 算法·理论

高斯消元:

e.g P3389 【模板】高斯消元法

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <cmath>
#define MAXN 110
#define eps 0.00001
using namespace std;

struct node {
    double b[MAXN][MAXN];
} Martix;

inline int read() {
    register int x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return x * f;
}

int n;
double ans[MAXN];
bool illegal;

inline void Gauss() {
    for (int i = 1; i <= n; i++) {
        int r = i;
        for (int x = i + 1; x <= n; x++) {
            if (fabs(Martix.b[x][i]) > fabs(Martix.b[r][i])) {
                r = x;
            }
        }
        if (fabs(Martix.b[r][i]) < eps) {
            printf("No Solution\n");
            illegal = true;
            return;
        }
        if (r != i) {
            for (int x = 1; x <= n + 1; x++)
                swap(Martix.b[i][x], Martix.b[r][x]);
        }
        double div = Martix.b[i][i];
        for (int x = i; x <= n + 1; x++)
            Martix.b[i][x] /= div;
        for (int x = i + 1; x <= n; x++) {
            div = Martix.b[x][i];
            for (int j = i; j <= n + 1; j++)
                Martix.b[x][j] -= Martix.b[i][j] * div;
        }
    }
    ans[n] = Martix.b[n][n + 1];
    for (int x = n - 1; x >= 1; x--) { ///注:高斯消元中的回带解方程在最后一步才进行,不要将其放置for循环中。 
        ans[x] = Martix.b[x][n + 1];
        for (int j = x + 1; j <= n; j++)
            ans[x] -= Martix.b[x][j] * ans[j];
    } ///高斯消元中的回带相当于已知x[i + 1]~x[n]然后代入第i个方程中反求出x[i]; 
}

int main() {
    n = read();
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n + 1; j++) {
            scanf("%lf", &Martix.b[i][j]);
        }
    }
    Gauss();
    if (!illegal) {
        for (int i = 1; i <= n; i++)
            printf("%.2lf\n", ans[i]);
    }
    return 0;
}