Cod sursa(job #2301330)

Utilizator zdavid112zIon David-Gabriel zdavid112z Data 12 decembrie 2018 20:46:26
Problema Algoritmul lui Gauss Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
#include <bits/stdc++.h>
#define eps 1e-8

using namespace std;

int n, m;
double mat[310][310];
double rez[310];

int main()
{
    freopen("gauss.in", "r", stdin);
    freopen("gauss.out", "w", stdout);
    scanf("%d%d", &n, &m);
    for(int i = 0; i < n; i++)
        for(int j = 0; j <= m; j++)
            scanf("%lf", &mat[i][j]);
    int l = 0, c = 0;
    while(l < n && c < m)
    {
        if(abs(mat[l][c]) < eps)
        {
            int ok = 0;
            for(int i = l + 1; i < n; i++)
            {
                if(abs(mat[l][c]) >= eps)
                {
                    for(int j = c; j <= m; j++)
                        swap(mat[l][j], mat[i][j]);
                    ok = 1;
                    break;
                }
            }
            if(ok == 0)
            {
                c++;
                break;
            }
        }
        for(int j = c + 1; j <= m; j++)
            mat[l][j] /= mat[l][c];
        mat[l][c] = 1;
        for(int i = l + 1; i < n; i++)
        {
            if(abs(mat[i][c]) < eps)
                continue;
            for(int j = c + 1; j <= m; j++)
                mat[i][j] -= mat[i][c] * mat[l][j];
            mat[i][c] = 0;
        }
        l++;
        c++;
    }
    l = n - 1;
    c = m - 1;
    while(l >= 0 && c >= 0)
    {
        while(c >= 0 && abs(mat[l][c]) >= eps)
            c--;
        c++;
        double expr = 0;
        for(int i = c + 1; i < m; i++)
            expr -= mat[l][i] * rez[i];
        expr += mat[l][m];
        if(c == m && abs(expr) >= 0)
        {
            printf("Imposibil");
            return 0;
        }
        rez[c] = expr / mat[l][c];
        c--;
        l--;
    }
    for(int i = 0; i < m; i++)
        printf("%f ", rez[i]);
    return 0;
}