Cod sursa(job #806045)

Utilizator tzipleatudTudor Tiplea tzipleatud Data 1 noiembrie 2012 19:00:30
Problema Algoritmul lui Gauss Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.04 kb
#include <fstream>
#include <iomanip>
#define NM 310
#define INF 0x3f3f3f3f

using namespace std;

ifstream f("gauss.in");
ofstream g("gauss.out");

const double EPS=0.0000001;
const double Z0=0.0;

bool Equal (const double& a, const double& b)
{
    return (-EPS<(a-b) && (a-b)<EPS);
}

int N,M;
int i,j;
int x;
int l,c;

double A[NM][NM];
double X[NM];
double Y;

void SwapLine (int l1, int l2)
{
    for (int j=1; j<=M+1; j++)
        swap(A[l1][j],A[l2][j]);
}

void Extract (int D, int S, int C)
{
    int Y=A[D][C];
    for (int j=1; j<=M+1; j++)
        A[D][j]-=A[S][j]*Y;
}

int main ()
{
    f >> N >> M;

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

    for (j=1; j<=M; j++)
        X[j]=INF;

    l=c=1;

    while (l<=N && c<=M)
    {
        for (x=l; x<=N; x++)
            if (A[x][c]!=0)
                break;

        if (x>N)
        {
            X[c]=Z0;
            c++;
            continue;
        }

        SwapLine(l,x);

        Y=A[l][c];

        for (j=1; j<=M+1; j++)
            A[l][j]/=1.0*Y;

        for (x=l+1; x<=N; x++)
            Extract(x,l,c);

        l++;
        c++;
    }

    for (i=1; i<=N; i++)
    {
        x=0;
        for (j=1; j<=M+1; j++)
            if (!Equal(A[i][j],Z0))
                x++;

        if (x==1 && !Equal(A[i][M+1],Z0))
        {
            g << "Imposibil" << '\n';
            f.close();
            g.close();

            return 0;
        }
    }

    for (i=N; i>=1; i--)
    {
        int p=0;
        for (j=1; j<=M; j++)
            if (!Equal(A[i][j],Z0) && X[j]==INF)
            {
                p=j;
                break;
            }

        if (p==0) continue;

        X[p]=A[i][M+1];
        for (j=1; j<=M; j++)
            if (j!=p)
                X[p]-=A[i][j]*X[j];
    }

    for (j=1; j<=M; j++)
        g << fixed << setprecision(8) << X[j] << ' ';

    g << '\n';

    f.close();
    g.close();

    return 0;
}