Cod sursa(job #3199343)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 1 februarie 2024 15:33:10
Problema Algoritmul lui Gauss Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.01 kb
#include <bits/stdc++.h>
using namespace std;
const char nl = '\n';
const char sp = ' ';
const int inf = 0x3f3f3f3f;
const int mod = 1e9 + 7;
const char out[2][4]{ "NO", "YES" };
#define all(a) a.begin(), a.end()
using ll = long long;
ifstream fin("gauss.in");
ofstream fout("gauss.out");

const int nmax = 300;
int n, m;
vector<vector<long double>> a;
vector<long double> x;
const long double eps = 1e-10;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    fin >> n >> m;
    a.assign(n + 1, vector<long double>(m + 2));
    x.assign(m + 1, 0);
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m + 1; ++j) {
            fin >> a[i][j];
        }
    }
    int i = 1, j = 1;
    while (i <= n && j <= m) {
        int x = i;
        while (x <= n && abs(a[x][j]) < eps) {
            ++x;
        }
        if (x > n) {
            ++j;
            continue;
        }
        swap(a[i], a[x]);
        long double d = a[i][j];
        for (int y = j; y <= m + 1; ++y) {
            a[i][y] /= d;
        }
        for (int u = i + 1; u <= n; ++u) {
            long double z = a[u][j] / a[i][j];
            for (int w = j; w <= m + 1; ++w) {
                a[u][w] -= a[i][w] * z;
            }
        }
        ++i, ++j;
    }
    for (int i = n; i > 0; --i) {
        for (int j = 1; j <= m + 1; ++j) {
            if (abs(a[i][j]) >= eps) {
                if (j == m + 1) {
                    fout << "Imposibil";
                    return 0;
                }
                x[j] = a[i][m + 1];
                for (int k = j + 1; k <= m; ++k) {
                    x[j] -= x[k] * a[i][k];
                }
                break;
            }
        }
    }
    //for (int i = 1; i <= n; ++i) {
    //    for (int j = 1; j <= m + 1; ++j) {
    //        cout << a[i][j] << sp;
    //    }
    //    cout << nl;
    //}
    //cout << nl;
    for (int j = 1; j <= m; ++j) {
        fout << fixed << setprecision(10) << x[j] << sp;
    }
}