Cod sursa(job #743489)

Utilizator warchildmdMihail Burduja warchildmd Data 4 mai 2012 17:58:57
Problema Algoritmul lui Gauss Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.76 kb
#include <cstdio>

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]);
            if (sistem[i][j] != 0)
            {
                justZeros = false;
            }
        }
        scanf("%lf", &Y[i]);
        if (Y[i] != 0 && justZeros == true)
        {
            bSol = false;
        }
    }

    int MAXLINE = 1;

    if(bSol)
    {
        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];
                //printf("%d %d - %lf\n", i, c, ratio);
                for(int k = j; k <= M; k++)
                {
                    //printf("%lf - %lf * %lf\n", sistem[c][k], ratio, sistem[i][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++)
        {
            for(int j = 1; j <= M; j++)
            {
                printf("%lf ", sistem[i][j]);
            }
            printf("\n");
        }*/
        for (int i = MAXLINE; i >= 1; i--)
        {
            if(sistem[i][i] == 0)
            {
                continue;
            }
            double DIFF = Y[i];
            for(int j = i + 1; j <= M; j++)
            {
                DIFF -= sistem[i][j] * X[j];
            }
            X[i] = DIFF / sistem[i][i];
        }
        for(int i = 1; i <= M; i++)
        {
            printf("%.10lf ", X[i]);
        }
    }
    else
    {
        printf("Imposibil\n");
    }

    return 0;
}