[Algorithm] Gaussian elimination

Preface
pushed today to the Los Valley Gaussian elimination template .
Play a bit and make a blog
complexity
is actually a very violent algorithm
\ (\ Theta (n ^ 3 ) \)
algorithm to explain the
referenceprimary MathematicsKnowledge, we know that there are two ways of elimination: the elimination subtraction, into the elimination
and then into the computer to achieve the elimination seems a bit complicated
so we chose subtraction elimination and matrix storage equation
chestnuts:
\ (\ left \ {\ begin {matrix}
\ \ x + 2y + 3z = 0 \\ 4x + 5y + 6z = 0 \\ 7x + 8y + 9z = 0 \ end {matrix} \ right \} \) we convert it to
\ (\ left \ {\ begin {matrix} 1 & 2 & 3 & | & 0 \\ 4 & 5 & 6 & | & 0 \\ 7 & 8 & 9 & | & 0 \ end {matrix} \ right \} \)
that is the n-th equation of the n + 1 item formulas for constant term
but choose which formula to other formulas elimination of it?
In order to minimize the error, we chose the biggest equation coefficients to be eliminated.
Proof: think about it, we obviously want the rest of the larger equation coefficients, so we must select the "maximum coefficient formula to be eliminated,"
Suppose we want to eliminate item i, Ke us to put the transducers to the i line (easy to operate)
and then eliminate other items, and the results
last from the beginning of last expression, brought forward one by one, lift the value of the variable other
tips: when working, the formula that you want to eliminate all that divided themselves item
Code

#include <cstdio>
#include <cmath>
#include <algorithm>
#define ll long long 
#define ld long double

ll read(){
    ll x = 0; int zf = 1; char ch = ' ';
    while (ch != '-' && (ch < '0' || ch > '9')) ch = getchar();
    if (ch == '-') zf = -1, ch = getchar();
    while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); return x * zf;
}

ld mat[105][106];
ld res[105];

bool guass(int n){
    int _max;
    for (int i = 0; i < n; ++i){
        _max = i;
        for (int j = i + 1; j < n; ++j)
            if (mat[_max][i] < mat[j][i]) _max = j;
        std::swap(mat[_max], mat[i]);
        ld tmp = mat[i][i];
        if (fabs(tmp) < 1e-8)
            return 0;
        for (int j = i; j <= n; ++j)
            mat[i][j] /= tmp;
        for (int j = i + 1; j < n; ++j){
            tmp = mat[j][i];
            for (int k = i; k <= n; ++k)
                mat[j][k] -= mat[i][k] * tmp;
        }
    }
    res[n - 1] = mat[n - 1][n];
    for (int i = n - 2; i >= 0; --i){
        res[i] = mat[i][n];
        for (int j = i + 1; j < n; ++j)
            res[i] -= res[j] * mat[i][j];
    }
    return 1;
}

int main(){
    int n = read();
    for (int i = 0; i < n; ++i)
        for (int j = 0; j <= n; ++j)
            mat[i][j] = read();
    if (guass(n)){
        for (int i = 0; i < n; ++i)
            printf("%.2Lf\n", res[i]);
    }
    else
        printf("No Solution");
    return 0;
}

Guess you like

Origin www.cnblogs.com/linzhengmin/p/10991617.html