Cod sursa(job #2568438)

Utilizator mihneacazCazacu Mihnea mihneacaz Data 3 martie 2020 22:52:57
Problema Algoritmul lui Gauss Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.34 kb
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <cmath>

using namespace std;

const int NMAX = 305;
const long double EPS1 = 1e-10;
const long double EPS2 = 1e-4;
const long double INF = 1.0 * 1e10;

ifstream cin("gauss.in");
ofstream cout("gauss.out");

long double a[NMAX][NMAX], init[NMAX][NMAX];
long double ans[NMAX];

bool IsZero1(long double a)
{
    return fabs(a) <= EPS1;
}

bool IsZero2(long double a)
{
    return fabs(a) <= EPS2;
}

void SwapLines(int x, int y, int m)
{
    for(int i = 1; i <= m; ++i) {
        swap(a[x][i], a[y][i]);
    }
}

int main() {
    int n, m;
    cin >> n >> m;
    m++;
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            cin >> a[i][j];
            init[i][j] = a[i][j];
        }
    }
    for (int c = 1; c < m; ++c) {
        int line = -1;
        for (int l = c; l <= n; ++l) {
            if (!IsZero1(a[l][c])) {
                line = l;
                break;
            }
        }
        if(line != -1) {
            long double rad1 = a[line][c];
            for (int cc = 1; cc <= m; ++cc) {
                a[line][cc] = a[line][cc] / rad1;
            }
            for (int ll = 1; ll <= n; ++ll) {
                long double rad2 = a[ll][c];
                for (int cc = c; cc <= m; ++cc) {
                    if (ll != line) {
                        a[ll][cc] = a[ll][cc] - rad2 * a[line][cc];
                    }
                }
            }
            SwapLines(line, c, m);
        } else {
            ans[c] = 0.0;
        }
    }
    for (int i = n + 1; i < m; ++i) {
        ans[i] = 0;
    }
    for (int l = 1; l <= n; ++l) {
        int cnt = 0;
        for (int c = 1; c < m; ++c) {
            if (IsZero1(a[l][c] - 1.0)) {
                cnt++;
                ans[c] = a[l][m];
            }
        }
        if (cnt == 0 && !IsZero1(a[l][m])) {
            cout << "Imposibil\n";
            return 0;
        }
    }
    for(int l = 1; l <= n; ++l) {
        long double sum = 0.0;
        for(int c = 1; c < m; ++c) {
            sum += 1.0 * ans[c] * init[l][c];
        }
        if(!IsZero2(init[l][m] - sum)) {
            cout << "Imposibil\n";
//           bool aaa = IsZero2(init[l][m] - sum);
            return 0;
        }
    }
    for(int i = 1; i < m; ++i) {
        cout << fixed << setprecision(8) << ans[i] << " ";
    }
    return 0;
}