【模板】高斯消元

Luogu P3389 【模板】高斯消元法

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#define MAX_N 105
#define EPS 1e-6
#define eq(x, y) (fabs((x) - (y)) < EPS)

using namespace std;

int n;
double a[MAX_N][MAX_N];

bool gauss(double a[][MAX_N], int n) {
    for (int i = 1; i <= n; i++) {
        int t = i;
        for (int j = i + 1; j <= n; j++) {
            if (fabs(a[j][i]) > fabs(a[t][i])) {
                t = j;
            }
        }
        if (eq(a[t][i], 0)) {
            return false;
        }
        if (t != i) {
            for (int j = 1; j <= n + 1; j++) {
                swap(a[i][j], a[t][j]);
            }
        }
        for (int j = i + 1; j <= n; j++) {
            double f = a[j][i] / a[i][i];
            for (int k = i; k <= n + 1; k++) {
                a[j][k] -= a[i][k] * f;
            }
        }
    }
    for (int i = n; i >= 1; i--) {
        for (int j = 1; j < i; j++) {
            a[j][n + 1] -= a[i][n + 1] * a[j][i] / a[i][i];
        }
        a[i][n + 1] /= a[i][i];
    }
    return true;
}

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n + 1; j++) {
            scanf("%lf", &a[i][j]);
        }
    }
    if (!gauss(a, n)) {
        printf("No Solution\n");
        return 0;
    }
    for (int i = 1; i <= n; i++) {
        printf("%.2f\n", a[i][n + 1]);
    }
}
点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注