zoukankan      html  css  js  c++  java
  • Gauss高斯消元——模板

    就是线性代数的初等行变化:

    • 倍加。
    • 倍乘。
    • 交换行。
    #include <bits/stdc++.h>
    #define mp make_pair
    #define pb push_back
    
    using namespace std;
    
    typedef long long ll;
    typedef pair<int, int> pii;
    typedef unsigned long long ull;
    
    const double pi = acos(-1.0);
    const double eps = 1e-7;
    const int inf = 0x3f3f3f3f;
    
    inline ll read() {
        ll f = 1, x = 0;
        char c = getchar();
        while(c < '0' || c > '9') {
            if(c == '-')    f = -1;
            c = getchar();
        }
        while(c >= '0' && c <= '9') {
            x = (x << 1) + (x << 3) + (c ^ 48);
            c = getchar();
        }
        return f * x;
    }
    
    const int N = 110;
    
    double maze[N][N], ans[N];
    int n;
    
    bool Gauss() {
        for(int i = 1; i <= n; i++) {
            int max_r = i;
            for(int j = i + 1; j <= n; j++)
                if(fabs(maze[max_r][i]) < fabs(maze[j][i]))
                    max_r = j;
            if(fabs(maze[max_r][i]) < eps)  return true;
            if(max_r != i)  swap(maze[i], maze[max_r]);
            double temp = maze[i][i];
            for(int j = i; j <= n + 1; j++)
                maze[i][j] /= temp;
            for(int j = i + 1; j <= n; j++) {
                temp = maze[j][i];
                for(int k = i; k <= n + 1; k++)
                    maze[j][k] -= temp * maze[i][k];
            }
        }
        for(int i = n; i >= 1; i--) {
            ans[i] = maze[i][n + 1];
            // ans[(int)maze[i][0]] = maze[i][n + 1];
            for(int j = 1; j < i; j++) {
                double temp = maze[j][i];
                maze[j][i] -= temp;
                maze[j][n + 1] -= maze[i][n + 1] * temp;
            }
        }
        return false;
    }
    
    int main () {
        // freopen("in.txt", "r", stdin);
        // freopen("out.txt", "w", stdout);
        // ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
        n = read();
        for(int i = 1; i <= n; i++) {
            maze[i][0] = i;
            for(int j = 1; j <= n + 1; j++)
                maze[i][j] = read();
        }
        if(Gauss()) {
            puts("No Solution");
            return 0;
        }
        for(int i = 1; i <= n; i++)
            printf("%.2f
    ", ans[i]);
        return 0;
    }
    
  • 相关阅读:
    python字符串格式化
    MFC----任务管理器的制作
    高斯消元方程组
    linux qq下载
    python——tuple元组
    Codeforces 515C. Drazil and Factorial
    HDU 1102 Constructing Roads (最小生成树)
    hdu 01背包汇总(1171+2546+1864+2955。。。
    HDU 3392 Pie(DP)
    HDU 1024
  • 原文地址:https://www.cnblogs.com/lifehappy/p/13192837.html
Copyright © 2011-2022 走看看