Cod sursa(job #2570706)

Utilizator PopoviciRobertPopovici Robert PopoviciRobert Data 4 martie 2020 18:44:12
Problema Algoritmul lui Gauss Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <bits/stdc++.h>
#define lsb(x) (x & (-x))
#define ll long long
#define ull unsigned long long
#define uint unsigned int


using namespace std;

const double eps = 1e-6;


int main() {
#ifdef HOME
    ifstream cin("A.in");
    ofstream cout("A.out");
#endif
    ifstream cin("gauss.in");
    ofstream cout("gauss.out");
    int i, j, n, m;
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n >> m;
    vector <vector <double>> eqs(n + 1, vector <double>(m + 2));
    for(i = 1; i <= n; i++) {
        for(j = 1; j <= m + 1; j++) {
            cin >> eqs[i][j];
        }
    }
    int l = 1, c = 1;
    while(l <= n && c <= m) {
        i = l;
        while(i <= n && fabs(eqs[i][c]) < eps) {
            i++;
        }
        if(i == n + 1) {
            c++;
        }
        else {
            for(j = c; j <= m + 1; j++) {
                swap(eqs[i][j], eqs[l][j]);
            }
            for(j = m + 1; j >= c; j--) {
                eqs[l][j] /= eqs[l][c];
            }
            for(i = l + 1; i <= n; i++) {
                for(j = m + 1; j >= c; j--) {
                    eqs[i][j] -= eqs[i][c] * eqs[l][j];
                }
            }
            l++, c++;
        }
    }
    vector <double> sol(m + 1);
    for(i = n; i >= 1; i--) {
        int p = 1;
        while(p <= m && fabs(eqs[i][p]) < eps) {
            p++;
        }
        if(p == m + 1) {
            if(fabs(eqs[i][m + 1]) > eps) {
                cout << "Imposibil";
                return 0;
            }
        }
        else {
            sol[p] = eqs[i][m + 1];
            for(j = p + 1; j <= m; j++) {
                sol[p] -= eqs[i][j] * sol[j];
            }
        }
    }
    for(i = 1; i <= m; i++) {
        cout << fixed << setprecision(8) << sol[i] << " ";
    }

    return 0;
}