Cod sursa(job #2255143)

Utilizator zdavid112zIon David-Gabriel zdavid112z Data 6 octombrie 2018 14:49:16
Problema Algoritmul lui Gauss Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include <bits/stdc++.h>
#define eps 1e-8

using namespace std;

double sol[305];
double mat[305][305];
int n, m;

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 lc = 0, cc = 0;
    while(lc < n && cc < m)
    {
        if(abs(mat[lc][cc]) < eps)
        {
            int ok = 0;
            for(int i = lc + 1; i < n; i++)
            {
                if(abs(mat[i][cc]) >= eps)
                {
                    for(int j = cc; j <= m; j++)
                        swap(mat[i][j], mat[lc][j]);
                    ok = 1;
                    break;
                }
            }
            if(ok == 0) /// nec sec
            {
                cc++;
                continue;
            }
        }
        for(int i = cc + 1; i <= m; i++)
            mat[lc][i] /= mat[lc][cc];
        mat[lc][cc] = 1;
        for(int i = lc + 1; i < n; i++)
        {
            for(int j = cc + 1; j <= m; j++)
                mat[i][j] -= mat[i][cc] * mat[lc][j];
            mat[i][cc] = 0;
        }
        lc++; cc++;
    }
    int ok = 1;
    for(int i = n - 1; i >= 0; i--)
    {
        int j;
        for(j = 0; j <= m && abs(mat[i][j]) < eps; j++);
        if(j == m + 1) /// 0 = 0
            continue;
        else if(j == m) /// 0 = ?
        {
            ok = 0;
            break;
        }
        else
        {
            double val = 0;
            for(int k = j + 1; k < m; k++)
                val += mat[i][k] * sol[k];
            sol[j] = mat[i][m] - val;
        }
    }
    if(ok == 0)
        printf("Imposibil");
    else
    {
        for(int i = 0; i < m; i++)
            printf("%.10f ", sol[i]);
    }
    return 0;
}