• 【模板】高斯消元


    代码如下

    #include <bits/stdc++.h>
    using namespace std;
    const double eps = 1e-7;
    
    struct matrix {
    	vector<vector<double>> mat;
    	int n, m;
    	matrix(int n, int m) : n(n), m(m) {
    		mat.resize(n + 1, vector<double>(m + 1, 0));
    	}
    	vector<double> &operator[](int x) {
    		return mat[x];
    	}
    };
    
    bool gauss(matrix &a, int n) {
    	for (int i = 1; i <= n; i++) {
    		int p = i;
    		for (int j = i + 1; j <= n; j++) {
    			if (fabs(a[p][i]) < fabs(a[j][i])) {
    				p = j;
    			}
    		}
    		if (p != i) {
    			swap(a[p], a[i]);
    		}
    		if (fabs(a[p][i]) < eps) {
    			return 0;
    		}
    		for (int j = i + 1; j <= n; j++) {
    			double factor = a[j][i] / a[i][i];
    			for (int k = i; k <= n + 1; k++) {
    				a[j][k] -= factor * a[i][k];
    			}
    		}
    	}
    	for (int i = n; i >= 1; i--) {
    		for (int j = i + 1; j <= n; j++) {
    			a[i][n + 1] -= a[j][n + 1] * a[i][j];
    		}
    		a[i][n + 1] /= a[i][i];
    	}
    	return 1;
    }
    
    int main() {
    	ios::sync_with_stdio(false);
    	cin.tie(0), cout.tie(0), cout.setf(ios::fixed);
    	int n;
    	cin >> n;
    	matrix a(n, n + 1);
    	for (int i = 1; i <= n; i++) {
    		for (int j = 1; j <= n + 1; j++) {
    			cin >> a[i][j];
    		}
    	}
    	if (gauss(a, n) == 0) {
    		cout << "No Solution" << endl;
    	} else {
    		for (int i = 1; i <= n; i++) {
    			cout << setprecision(2) << a[i][n + 1] << endl;
    		}
    	}
    	return 0;
    }
    
  • 相关阅读:
    vue学习6
    vue学习5
    vue学习3
    vue学习2
    vue学习1
    idea快速查找和替换快捷键
    mysql三元表达式
    1 Java Lambda表达式forEach无法跳出循环的解决思路
    6 Mybatis Plus and 和 or,分页Page使用
    4 Mybatis Plus使用redis作为二级缓存
  • 原文地址:https://www.cnblogs.com/wzj-xhjbk/p/10819611.html
Copyright © 2020-2023  润新知