Cod sursa(job #3185369)

Utilizator verde.cristian2005Verde Flaviu-Cristian verde.cristian2005 Data 18 decembrie 2023 19:48:15
Problema Algoritmul lui Gauss Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.24 kb
#include <bits/stdc++.h>
using namespace std;

#ifndef HOME
    ifstream in("gauss.in");
    ofstream out("gauss.out");
    #define cin in
    #define cout out
#endif

long double coef[301][302];
const long double eps = 1e-8;
long double ans[301];

int main()
{
#ifdef HOME
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#endif
    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= m; i++)
        for(int j = 1; j <= n + 1; j++)
            cin >> coef[i][j];
    int lastEq = 1;
    for(int j = 1; j <= n; j++)
    {
        for(int i = lastEq; i <= m; i++)
            if(coef[i][j] >= eps || coef[i][j] <= -eps)
            {
                for(int k = 1; k <= n + 1; k++)
                    swap(coef[lastEq][k], coef[i][k]);
                break;
            }
        if(coef[j][j] >= eps || coef[j][j] <= -eps)
        {
            long double x = coef[lastEq][j];
            for(int k = 1; k <= n + 1; k++)
                coef[lastEq][k] /= x;
            for(int i = 1; i <= m; i++)
                if(i != j)
                {
                    long double x = coef[i][j];
                    for(int k = 1; k <= n + 1; k++)
                        coef[i][k] -= coef[lastEq][k] * x;
                    /// bk -= ak * bj
                }
            lastEq++;
        }
    }
    /// -eps < (a - b) < eps
    /// b - eps < a < b + eps
    ///a - b >= eps
    ///a >= b + eps
    for(int i = 1; i <= m; i++)
    {
        bool ok = 0;
        for(int j = 1; j <= n; j++)
            ok |= (coef[i][j] <= -eps || coef[i][j] >= eps);
        if(ok == 0 && (coef[i][n + 1] <= -eps || coef[i][n + 1] >= eps))
        {
            cout << "Imposibil";
            return 0;
        }
    }
    for(int i = 1; i <= m; i++)
    {
        bool ok = 0;
        for(int j = 1; j <= n; j++)
            if(coef[i][j] <= -eps || coef[i][j] >= eps)
            {
                if(!ok)
                {
                    ok = 1;
                    ans[j] = coef[i][n + 1];
                }
                else
                    ans[j] = 0;
            }
    }
    for(int j = 1; j <= n; j++)
        cout << fixed << setprecision(8) << ans[j] << " ";
    return 0;
}