Cod sursa(job #2591967)

Utilizator andreiomd1Onut Andrei andreiomd1 Data 31 martie 2020 19:16:25
Problema Algoritmul lui Gauss Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.89 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("gauss.in");
ofstream g("gauss.out");

const int NMAX = 3e3 + 5;
const long double eps = 1e-8;

int N, M;

long double A[NMAX][NMAX], ans[NMAX];

int Chosen[NMAX];

static inline void Read ()
{
    f.tie(NULL);

    f >> M >> N;

    for(int i = 1; i <= M; ++i)
        for(int j = 1; j <= N + 1; ++j)
            f >> A[i][j];

    return;
}

static inline long double my_abs (long double X)
{
    if(X < (long double)0)
        return -X;

    return X;
}

static inline void Reconstruct ()
{
    for(int Eq = 1; Eq <= M; ++Eq)
        if(!Chosen[Eq])
            continue;
        else
            ans[Chosen[Eq]] = A[Eq][N + 1] / A[Eq][Chosen[Eq]];

    return;
}

static inline void GaussElimination ()
{
    for(int Eq = 1; Eq <= M; ++Eq)
    {
        int pos = 0;

        for(int Var = 1; Var <= N + 1 && !pos; ++Var)
            if(my_abs(A[Eq][Var]) > eps)
                pos = Var;

        if(!pos)
            continue;

        if(pos == N + 1)
        {
            g << "Imposibil" << '\n';

            exit(0);

            return;
        }

        Chosen[Eq] = pos;

        for(int i = 1; i <= M; ++i)
        {
            if(i == Eq)
                continue;

            if(my_abs(A[i][pos]) < eps)
                continue;

            long double Coef = A[i][pos] / A[Eq][pos];

            for(int Var = 1; Var <= N + 1; ++Var)
                A[i][Var] -= Coef * A[Eq][Var];
        }
    }

    Reconstruct();

    return;
}

static inline void Write ()
{
    g << setprecision(10) << fixed;

    for(int Var = 1; Var <= N; ++Var)
    {
        g << ans[Var];

        if(Var != N)
            g << ' ';
    }

    g << '\n';

    return;
}

int main()
{
    Read();

    GaussElimination();

    Write();

    return 0;
}