Cod sursa(job #2824365)

Utilizator UnknownPercentageBuca Mihnea-Vicentiu UnknownPercentage Data 1 ianuarie 2022 21:49:20
Problema Algoritmul lui Gauss Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <bits/stdc++.h>

using namespace std;

inline void Open(const string Name) {
    #ifndef ONLINE_JUDGE
        (void)!freopen((Name + ".in").c_str(), "r", stdin);
        (void)!freopen((Name + ".out").c_str(), "w", stdout);
    #endif
}

const long double EPS = 1e-10;;

long double a[303][303];
long double ans[303];

int where[303];
int N, M;

void gauss() {
    memset(where, -0x1, sizeof(where));

    for(int col = 1, row = 1;col <= M && row <= N;col++) {
        int sel = row;
        for(int i = row;i <= N;i++)
            if(abs(a[i][col]) > abs(a[sel][col]))
                sel = i;

        if(abs(a[sel][col]) < EPS)
            continue;

        for(int i = col;i <= M + 1;i++)
            swap(a[sel][i], a[row][i]);
        where[col] = row;

        for(int i = 1;i <= N;i++)
            if(i != row) {
                long double c = a[i][col] / a[row][col];
                for(int j = col;j <= M + 1;j++)
                    a[i][j] -= a[row][j] * c;
            }

        ++row;
    }

    memset(ans, 0, sizeof(ans));
    for(int i = 1;i <= M;i++)
        if(where[i] != -1)
            ans[i] = a[where[i]][M + 1] / a[where[i]][i];

    for(int i = 1;i <= N;i++) {
        long double sum = 0;
        for(int j = 1;j <= M;j++)
            sum += ans[j] * a[i][j];
        if(abs(sum - a[i][M + 1]) > EPS) {
            cout << "Imposibil";
            exit(0);
        }
    }
}

void solve() {
    cin >> N >> M;
    for(int i = 1;i <= N;i++)
        for(int j = 1;j <= M + 1;j++)
            cin >> a[i][j];

    gauss();

    cout << fixed << setprecision(10);
    for(int i = 1;i <= M;i++)
        cout << ans[i] << " ";
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    Open("gauss");

    int T = 1;
    for(;T;T--) {
        solve();
    }

    return 0;
}