Cod sursa(job #2497005)

Utilizator Kln1000Ciobanu Bogdan Kln1000 Data 21 noiembrie 2019 22:31:22
Problema Algoritmul lui Gauss Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.36 kb
#include <iostream>
#include <fstream>
#include <iomanip>

std::ifstream f("gauss.in");
std::ofstream t("gauss.out");

#define NMAX 310
#define EPSILON 1e8

template <typename T>
using Matrix = T[NMAX][NMAX];

template <typename T>
using Vector = T[NMAX];

int main() {
    // n is the number of equations, m the number of unknowns
    Matrix<double> A = {};
    Vector<double> b = {};
    Vector<double> x = {};
    int n, m;

    f >> n >> m;
/*
    if (n > m) {
        t << "Imposibil\n";
        return 0;
    }
*/
    auto abs = [](double target) {
        return target < 0 ? -target : target;
    };

    auto subtract_line_with_scalar = [&A, &b, m](int dst, int src, double scalar, int start = 0) mutable {
        for (int i = start; i < m; ++i)
            A[dst][i] -= A[src][i] * scalar;

        b[dst] -= b[src] * scalar;
    };

    auto divide_line_with_scalar = [&A, &b, m](int dst, double scalar, int start = 0) mutable {
        for (int i = start; i < m; ++i)
            A[dst][i] /= scalar;

        b[dst] /= scalar;
    };

    // reading the matrix and results
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j)
            f >> A[i][j];
        f >> b[i];
    }

    for (int i = 0; i < m; ++i) {  // for each column
        divide_line_with_scalar(i, A[i][i], i); // no pivoting, but scaling
        for (int j = i + 1; j < n; ++j) { // rest to 0
            subtract_line_with_scalar(j, i, A[j][i], i);
        }

    }
    /*
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j)
            std::cout << A[i][j] << " ";
        std::cout << " | " << b[i] << " : ";
    }
    */
    double sigma;
    // now perform back substitution
    for (int i = m - 1; i >= 0; --i) {
        sigma = .0;
        for (int j = n - 1; j > i; --j) {
            sigma += x[j] * A[i][j];
        }
        if (sigma < abs(EPSILON) && A[i][i] < abs(EPSILON) && b[i] > EPSILON) {
            t << "Imposibil\n";
            return 0;
        }
        x[i] = (b[i] - sigma) / A[i][i];
    }

    sigma = .0;

    for (int i = 0; i < m; ++i)
        sigma += x[i] * A[0][i];

    if (sigma != b[0]) {
        t << "Imposibil\n";
        return 0;
    }

    t << std::setprecision(10) << std::fixed;
    for (int i = 0; i < m; ++i)
        t << x[i] << " ";

    return 0;
}