Cod sursa(job #806083)

Utilizator tzipleatudTudor Tiplea tzipleatud Data 1 noiembrie 2012 20:02:42
Problema Algoritmul lui Gauss Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 kb
#include <fstream>
#include <cstdio>
#include <iomanip>
#define NM 310
#define INF 0x3f3f3f3f

using namespace std;

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)
{
    double Y=A[D][C];
    for (int j=1; j<=M+1; j++)
        A[D][j]-=A[S][j]*Y;
    //A[D][C]=0;
}

int main ()
{

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

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

    for (i=1; i<=N; i++)
        for (j=1; j<=M+1; j++)
            scanf("%lf",&A[i][j]);

    l=c=1;

    while (l<=N && c<=M)
    {
        for (x=l; x<=N; x++)
            if (A[x][c]<-EPS || A[x][c]>EPS)
                break;

        if (x>N)
        {
            c++;
            continue;
        }

        SwapLine(l,x);

        Y=A[l][c];

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

        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; j++)
            if (A[i][j]<-EPS || A[i][j]>EPS)
                x=1;
        if (x==1) continue;
        if (A[i][M+1]<-EPS || A[i][M+1]>EPS)
        {
            printf("Imposibil\n");
            return 0;
        }
    }

    for (i=N; i>=1; i--)
    {
        int p=0;
        for (j=1; j<=M; j++)
            if (A[i][j]<-EPS || A[i][j]>EPS)
            {
                p=j;
                break;
            }

        if (p==0) continue;

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

    for (j=1; j<=M; j++)
        printf("%.8lf ",X[j]);

    printf("\n");

    return 0;
}