Cod sursa(job #2594856)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 6 aprilie 2020 18:29:57
Problema Algoritmul lui Gauss Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 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];

    for (int i = 1, j = 1; i <= m && j <= n; j++) {
        int x; for (x = i; x <= m && abs(a[x][j]) < 1e-7; x++);
        if (x <= m) {
            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++;
        }
    }

    vector<double> ans(n + 1);
    for (int i = m; i >= 1; i--)
        for (int j = 1; j <= n + 1; j++)
            if (abs(a[i][j]) > 1e-7) {
                if (j == n + 1) {
                    fout << "Imposibil\n";
                    fout.close();
                    return 0;
                }
                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];
                break;
            }

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

    fout.close();
    return 0;
}