Cod sursa(job #1334021)

Utilizator maribMarilena Bescuca marib Data 3 februarie 2015 20:13:23
Problema Algoritmul lui Gauss Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <fstream>
#include <iomanip>
#define eps 0.00000000001
using namespace std;

int n, m;

double coef[301][301], sol[301];

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

void construieste()
{
    int i=1, j=1, x;
    while(i<=n&&j<=m)
    {
        for(x=i; x<=n; ++x)
        {
            if(coef[x][j]>eps||coef[x][j]<-eps)
                break;
        }
        if(x==n+1)
        {
            j++;
        }
        else
        {
            if(x!=i)
            {
                for(int k=1; k<=m+1; ++k)
                    swap(coef[i][k], coef[x][k]);
            }

            for(int k=m+1; k>j; --k)
            {
                coef[i][k]/=coef[i][j];
            }
            coef[i][j]=1;
            for(int k=i+1; k<=n; ++k)
            {
                for(int p=m+1; p>j; --p)
                    coef[k][p]-=coef[k][j]*coef[i][p];
                coef[k][j]=0;
            }
            i++; j++;
        }
    }
}

void gaseste()
{
    int x=0, j;
    for(int i=n; i>0; --i)
    {
        for(j=1; j<=m+1; ++j)
        {
            if(coef[i][j]>eps||coef[i][j]<-eps)
                break;
        }
        if(j==m+1)
        {
            out<<"Imposibil\n";
            x=1;
            break;
        }
        else if(j<=m)
        {
            sol[j]=coef[i][m+1];
            for(int k=j+1; k<=m; ++k)
            {
                sol[j] -= coef[i][k]*sol[k];
            }
        }
    }
    if(!x)
    {
        for(int i=1; i<=m; ++i)
        {
            out<<fixed<<setprecision(10)<<sol[i]<<" ";
        }
        out<<"\n";
    }
}

int main()
{
    in>>n>>m;
    for(int i=1; i<=n; ++i)
    {
        for(int j=1; j<=m+1; ++j)
        {
            in>>coef[i][j];
        }
    }
    construieste();
    gaseste();
    in.close();
    out.close();
    return 0;
}