Cod sursa(job #1781778)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 17 octombrie 2016 14:11:21
Problema Algoritmul lui Gauss Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax = 300 + 10;
const double eps = 1e-8;

double a[nmax][nmax], ans[nmax];

int n, m;
int p[nmax];

void read_input()
{
    freopen("gauss.in","r",stdin);

    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= m + 1; ++j)
            scanf("%lf", &a[i][j]);
}

void print_answer(bool type)
{
    freopen("gauss.out","w",stdout);

    if (type == 0)
        printf("Imposibil\n");
    else
    {
        for (int i = 1; i <= m; ++i)
            printf("%.10f ", ans[i]);
        printf("\n");
    }

    exit(0);
}

int compare(double a, double b)
{
    if (a + eps < b) return -1;
    if (b + eps < a) return 1;
    return 0;
}

void run_gauss(int n, int m)
{
    for (int i = 1; i <= n; ++i)
    {
        p[i] = 0;
        for (int j = 1; j <= m + 1 && !p[i]; ++j)
            if (compare(a[i][j], 0) != 0)
                p[i] = j;

        if (p[i] == m + 1)
            print_answer(0);

        if (p[i] == 0)
            continue;

        for (int k = 1; k <= n; ++k)
        {
            if (k == i || !p[i]) continue;

            double coef = a[k][p[i]] / a[i][p[i]];
            for (int j = 1; j <= m + 1; ++j)
                a[k][j] -= a[i][j] * coef;
        }
    }

    for (int i = 1; i <= m; ++i)
        if (p[i])
            ans[p[i]] = a[i][m+1] / a[i][p[i]];
}

int main()
{
    read_input();
    run_gauss(n, m);
    print_answer(1);

    return 0;
}