[Luogu] 高斯消元法

https://www.luogu.org/problemnew/show/P3389

模拟,消元

#include <bits/stdc++.h>

#define DB double

const int N = 110;
const DB eps = 1e-7;

DB A[N][N], Answer[N];
int n;

DB read() {DB a; scanf("%lf", &a); return a;}

int main() {
    std:: cin >> n;
    for(int i = 1; i <= n; i ++)
        for(int j = 1; j <= n + 1; j ++) A[i][j] = read();
    for(int i = 1; i <= n; i ++) {
        int r = i;
        for(int j = i + 1; j <= n; j ++) if(abs(A[j][i]) > abs(A[r][i])) r = i;
        if(abs(A[r][i]) <= eps) {std:: cout << "No Solution"; return 0;}
        if(i != r) std:: swap(A[i], A[r]);
        DB now = A[i][i];
        for(int j = i; j <= n + 1; j ++) A[i][j] /= now;
        for(int j = i + 1; j <= n; j ++) {
            DB Now = A[j][i];
            for(int k = i; k <= n + 1; k ++) A[j][k] -= Now * A[i][k];
        }
    }
    Answer[n] = A[n][n + 1];
    for(int i = n - 1; i >= 1; i --) {
        Answer[i] = A[i][n + 1];
        for(int j = n; j > n - (n - i); j --)
            Answer[i] -= Answer[j] * A[i][j];
    }
    for(int i = 1; i <= n; i ++) printf("%.2lf
", Answer[i]);
    
    return 0;
}
/*
3
1 -2 3 6
4 -5 6 12
7 -8 10 21
*/
原文地址:https://www.cnblogs.com/shandongs1/p/9074109.html