Cod sursa(job #2565261)

Utilizator Vaida_Radu_AndreiVaida Radu Andrei Vaida_Radu_Andrei Data 2 martie 2020 13:07:00
Problema Algoritmul lui Gauss Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.13 kb
#include <cstdio>
#define nMax 324

using namespace std;

const double eps=0.0000001;
int ecs,unks;
double coefs[nMax][nMax],sol[nMax];

int read() {
    int i,j;
    scanf("%d%d",&ecs,&unks);
    for(i=0;i<ecs;++i) {
        for(j=0;j<=unks;++j) {
            scanf("%lf",&coefs[i][j]);
        }
    }
    return 0;
}

void swp(double&x,double&y) {
    x-=y;
    y+=x;
    x=y-x;
}

void swpL(int l1,int l2) {
    int i;
    for(i=0;i<=unks;++i) {
        swp(coefs[l1][i],coefs[l2][i]);
    }
}

int change(int iEc,int iUnk) {
    int iNew;
    for(iNew=iEc;iNew<ecs;++iNew) {
        if(coefs[iNew][iUnk]<=-eps||coefs[iNew][iUnk]>=eps) {
            break;
        }
    }
    if(iNew==ecs) {
        return 0;
    }
    if(iNew!=iEc) {
        swpL(iNew,iEc);
    }
    return 1;
}

void make1(int iEc,int iUnk) {
    int i;
    for(i=iUnk+1;i<=unks;++i) {
        coefs[iEc][i]/=coefs[iEc][iUnk];
    }
    coefs[iEc][iUnk]=1;
}

void adv(int iEc,int iUnk) {
    int iE,iU;
    make1(iEc,iUnk);
    for(iE=iEc+1;iE<ecs;++iE) {
        for(iU=iUnk+1;iU<=unks;++iU) {
            coefs[iE][iU]-=coefs[iEc][iU]*coefs[iE][iUnk];
        }
        coefs[iE][iUnk]=0.0;
    }
}

void go() {
    int iEc,iUnk;
    for(iEc=0,iUnk=0;iEc<ecs&&iUnk<unks;++iUnk) {
        if(!change(iEc,iUnk)) {
            continue;
        }
        adv(iEc,iUnk);
        ++iEc;
    }
}

void sub(int iEc,int iUnk) {
    int i;
    for(i=0;i<iEc;++i) {
         coefs[i][unks]-=coefs[i][iUnk]*sol[iUnk];
    }
}

int goBack() {
    int iEc,iUnk;
    for(iUnk=unks+1,iEc=ecs-1;iEc>=0;--iEc) {
        for(;iUnk>0&&(coefs[iEc][iUnk-1]>eps||coefs[iEc][iUnk-1]<-eps);--iUnk) {
        }
        if(iUnk==unks) {
            return 1;
        }
        sol[iUnk]=coefs[iEc][unks];
        sub(iEc,iUnk);
    }
    return 0;
}

int solve() {
    go();
    return goBack();
}

void error() {
    printf("Imposibil");
}

void display() {
    int i;
    for(i=0;i<unks;++i) {
        printf("%.10lf ",sol[i]);
    }
}

int main() {
    freopen("gauss.in","r",stdin);
    freopen("gauss.out","w",stdout);
    read();
    if(solve()) {
        error();
        return 1;
    }
    display();
    return 0;
}