Cod sursa(job #743504)

Utilizator warchildmdMihail Burduja warchildmd Data 4 mai 2012 18:43:28
Problema Algoritmul lui Gauss Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.46 kb
#include <cstdio>

#define ERROR 0.0000001

int N, M;
double sistem[301][301];
double X[301];
double Y[301];

inline void swap(int i, int j)
{
    double temp;
    for(int c = 1; c <= M; c++)
    {
        temp = sistem[i][c];
        sistem[i][c] = sistem[j][c];
        sistem[j][c] = temp;
    }
}

inline int find(int i, int j)
{
    for (int c = i; c <= N; c++)
    {
        if (sistem[c][j] != 0)
        {
            return c;
        }
    }
    return 0;
}

int main()
{
    freopen("gauss.in", "r", stdin);
    freopen("gauss.out", "w", stdout);

    scanf("%d %d", &N, &M);

    bool bSol = true;

    for(int i = 1; i <= N; i++)
    {
        bool justZeros = true;
        for(int j = 1; j <= M; j++)
        {
            scanf("%lf", &sistem[i][j]);
        }
        scanf("%lf", &Y[i]);
    }

    int MAXLINE = 1;
    int i, j;
    i = j = 1;
    while((j <= M) && (i <= N))
    {
        int x = find(i, j);
        if (x == 0)
        {
            j++;
            continue;
        }
        if (x > i)
        {
            swap(i, x);
        }
        double ratio = 0.00;
        for(int c = i + 1; c <= N; c++)
        {
            if (sistem[c][j] == 0)
            {
                continue;
            }
            ratio = sistem[c][j] / sistem[i][j];
            for(int k = j; k <= M; k++)
            {
                sistem[c][k] = sistem[c][k] - (ratio * sistem[i][k]);
            }
            Y[c] = Y[c] - (ratio * Y[i]);
        }
        MAXLINE = i;
        i++;
        j++;
    }
    for(int i = 1; i <= N; i++)
    {
        bool justZeros = true;
        for(int j = 1; j <= M; j++)
        {
            if((sistem[i][j] < -ERROR) || (sistem[i][j] > ERROR))
            {
                justZeros = false;
            }
        }
        if(((Y[i] > ERROR) || (Y[i] < -ERROR)) && (justZeros))
        {
            printf("Imposibil");
            return 0;
        }
    }
    i = j = M;
    while(i >= 1)
    {
        if((sistem[i][j] > -ERROR) && (sistem[i][j] < ERROR)) //is close to 0
        {
            j--;
            continue;
        }
        double DIFF = Y[i];
        for(int k = j + 1; k <= M; k++)
        {
            DIFF -= sistem[i][k] * X[k];
        }
        X[i] = DIFF / sistem[i][j];
        i--;
        j--;
    }
    for(int i = 1; i <= M; i++)
    {
        printf("%.10lf ", X[i]);
    }

    return 0;
}