Cod sursa(job #2785402)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 18 octombrie 2021 17:17:31
Problema Algoritmul lui Gauss Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.31 kb
#include <fstream>
#include <vector>
#include <iomanip>
using namespace std;

const int NMAX = 300;
const double EPS = 1e-12;
bool NotNull(double x) { return x < -EPS || x > EPS; }

vector<double> res;
vector<bool> determined;

void solveGauss(int N, int M, vector<vector<double>> sys) {
    res.resize(M + 1, 0);
    determined.resize(M + 1, true);
    int rank = 1;
    for(int col = 1; col <= M && rank <= N; col++) {
        for(int i = rank; i <= N; i++) {
            if(NotNull(sys[i][col])) {
                swap(sys[rank], sys[i]);
                break;
            }
        }
        if(NotNull(sys[rank][col]) == false) {
            continue;
        }
        long double ct = sys[rank][col];
        for(int j = rank; j <= M + 1; j++) {
            sys[rank][j] /= ct;
        }
        for(int i = 1; i <= N; i++) {
            if(NotNull(sys[i][col]) == false || i == rank) {
                continue;
            }
            long double ct = sys[i][col] / sys[rank][col];
            for(int j = rank; j <= M + 1; j++) {
                sys[i][j] -= ct * sys[rank][j];
            }
        }
        rank++;
    }
    for(int i = 1; i < rank; i++) {
        int f = 0, l = M;
        for(; f <= M; f++) {
            if(NotNull(sys[i][f])) {
                break;
            }
        }
        for(; l >= 1; l--) {
            if(NotNull(sys[i][l])) {
                break;
            }
        }
        if(f == l) {
            res[f] = sys[i][M + 1];
        } else {
            determined[f] = false;
        }
    }
    for(int i = rank + 1; i <= N; i++) {
        if(NotNull(sys[i][M + 1])) {
            determined[M] = false;
        }
    }
}

int main() {
    ifstream f("gauss.in"); ofstream g("gauss.out");
    int N, M; f >> N >> M;
    vector<vector<double>> sys(N + 1, vector<double>(M + 2));
    for(int i = 1; i <= N; i++) {
        for(int j = 1; j <= M + 1; j++) {
            f >> sys[i][j];
        }
    }
    solveGauss(N, M, sys);

    bool possible = true;
    for(int i = 1; i <= M; i++) {
        possible &= determined[i];
    }

    if(!possible) {
        g << "Imposibil\n";
    } else {
        for(int i = 1; i <= M; i++) {
            g << fixed << setprecision(10) << res[i] << ' ';
        }
    }

    return 0;
}