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;
    }
    
  • 相关阅读:
    SpringBoot入门系列
    日志收集系统-多线程消息队列
    阿里云ecs 服务器配置
    MySQL 表分区详解MyiSam引擎和InnoDb 区别(实测)
    Redis 3.2 Linux 环境集群搭建与java操作
    Java
    多线程编程-工具篇-BlockingQueue
    java常见面试题及答案 11-20(JVM篇)
    28.function_score自定义相关度分数算法
    27.四种常见的相关度分数优化方法
  • 原文地址:https://www.cnblogs.com/lifehappy/p/13192837.html
Copyright © 2011-2022 走看看