Cod sursa(job #3156318)

Utilizator lolismekAlex Jerpelea lolismek Data 11 octombrie 2023 10:48:00
Problema Algoritmul lui Gauss Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <algorithm>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <queue>
#include <stack>

using namespace std;

#define int long long
#define pii pair <int, int>

string filename = "gauss";

#ifdef LOCAL
    ifstream fin("input.in");
    ofstream fout("output.out");
#else
    ifstream fin(filename + ".in");
    ofstream fout(filename + ".out");
#endif

const int NMAX = 305;
const double EPS = 1e-10;

double coef[NMAX + 1][NMAX + 1];
double sol[NMAX + 1];

bool notNull(double x){
    return (x < -EPS || x > EPS);
}

signed main(){

    int n, m;
    fin >> n >> m;

    for(int i = 1; i <= n; i++){
        for(int j = 1; j <= m + 1; j++){
            fin >> coef[i][j];
        }
    }

    int i = 1, j = 1;

    while(i <= n && j <= m){
        int k = -1;
        for(int l = i; l <= n; l++){
            if(notNull(coef[l][j])){
                k = l;
                break;
            }
        }

        if(k == -1){
            ++j;
            continue;
        }

        for(int c = 1; c <= m; c++){
            swap(coef[i][c], coef[k][c]);
        }

        for(int c = m + 1; c >= j; c--){
            coef[i][c] /= coef[i][j];
        }

        for(int l = i + 1; l <= n; l++){
            for(int c = m + 1; c >= j; c--){
                coef[l][c] -= coef[l][j] * coef[i][c];
            }
        }

        i++, j++;
    }

    for(int l = n; l >= 1; l--){
        for(int c = 1; c <= m + 1; c++){
            if(notNull(coef[l][c])){
                if(c == m + 1){
                    fout << "Imposibil\n";
                    return 0;
                }

                sol[c] = coef[l][m + 1];
                for(int k = c + 1; k <= m; k++){
                    sol[c] -= sol[k] * coef[l][k];
                }

                break;
            }
        }
    }

    fout << fixed << setprecision(10);
    for(int c = 1; c <= m; c++){
        fout << sol[c] << ' ';
    }
    fout << '\n';

    return 0;
}