Cod sursa(job #2594812)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 6 aprilie 2020 17:31:29
Problema Algoritmul lui Gauss Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("gauss.in");
ofstream fout("gauss.out");

int main() {
    int m, n; fin >> m >> n;
    vector<vector<double>> a(m + 1, vector<double>(n + 2));
    for (int i = 1; i <= m; i++)
        for (int j = 1; j <= n + 1; j++)
            fin >> a[i][j];

    vector<bool> zero(n + 1);
    for (int i = 1, j = 1; i <= m && j <= n; j++) {
        int x; for (x = i; x <= m && !a[x][j]; x++);
        if (x > m)
            zero[j] = true;
        else {
            swap(a[i], a[x]);
            for (int x = i + 1; x <= m; x++)
                for (int y = j; y <= n + 1; y++)
                    a[x][y] -= a[i][y] * a[x][j] / a[i][j];
            i++;
        }
    }

    bool ok = true;
    vector<double> ans(n + 1);
    for (int i = min(m, n), j = n; j >= 1; j--)
        if (!zero[j]) {
            ans[j] = a[i][n + 1];
            for (int y = j + 1; y <= n; y++)
                ans[j] -= a[i][y] * ans[y];
            ans[j] /= a[i][j];
            bool bad = true;
            for (int y = j; y <= n; y++)
                if (ans[y] * a[i][y]) {
                    bad = false;
                    break;
                }
            if (bad && a[i][n + 1]) {
                ok = false;
                break;
            }
            i--;
        }

    fout << fixed << setprecision(10);
    if (ok)
        for (int j = 1; j <= n; j++)
            fout << ans[j] << ' ';
    else
        fout << "Imposibil";
    fout << '\n';

    fout.close();
    return 0;
}