Cod sursa(job #1093827)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 28 ianuarie 2014 17:39:57
Problema Algoritmul lui Gauss Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

const int N_EQ = 300;
const int N_NE = 300;

long double A[N_EQ + 1][N_NE + 1];
long double SOL[N_NE + 1];

int N, M;

void read()
{
    ifstream f("gauss.in");

    f >> N >> M;

    for ( int i = 1; i <= N; ++i )
    {
        for ( int j = 1; j <= M + 1; ++j )
                f >> A[i][j];
    }
}

void GaussianElimination()
{
    int i = 1, j = 1;

    while ( i <= N && j <= M )
    {
        int x = 0;

        for ( int k = i; k <= N; ++k )
        {
            if ( A[k][j] != 0 )
            {
                x = k;
                break;
            }
        }

        if ( x == 0 )
        {
            j++;
            continue;
        }

        for ( int k = 1; k <= M + 1; ++k )
        {
            swap( A[i][k], A[x][k] );
        }

        for ( int k = j + 1; k <= M + 1; ++k )
        {
            A[i][k] = A[i][k] / A[i][j];
        }

        A[i][j] = 1;

        for ( int l = i + 1; l <= N; ++l )
        {
            for ( int c = j + 1; c <= M + 1; ++c )
            {
                A[l][c] -= A[l][j] * A[i][c];
            }

            A[l][j] = 0;
        }

        i++;
        j++;
    }
}

void compute_values()
{
    ofstream g("gauss.out");

    for ( int i = N; i >= 1; i-- )
            for ( int j = 1; j <= M + 1; ++j )
            {
                if ( A[i][j] != 0 )
                {
                    if ( j == M + 1 )
                    {
                        g << "Imposibil\n";
                        return;
                    }

                    SOL[j] = A[i][M + 1];

                    for ( int k = j + 1; k <= M; ++k )
                            SOL[j] -= SOL[k] * A[i][k];

                    break;
                }
            }

    for ( int i = 1; i <= M; ++i )
            g << fixed << setprecision( 10 ) << SOL[i] << " ";
}

int main()
{
    read();
    GaussianElimination();
    compute_values();

    return 0;
}