Cod sursa(job #2563447)

Utilizator Vaida_Radu_AndreiVaida Radu Andrei Vaida_Radu_Andrei Data 1 martie 2020 11:37:29
Problema Algoritmul lui Gauss Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.25 kb
#include <cstdio>
#define nMax 324
#define eps 1>>10

using namespace std;

int ecs,unks;
double coefs[nMax][nMax];
int compatibility;

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

void set() {
    compatibility=1;
}

void 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]);
        }
    }
}

void change(int p1,int p2) {
    int i;
    for(i=0;i<=unks;++i) {
        swp(coefs[p1][i],coefs[p2][i]);
    }
}

char changeSuccess(int pos) {
    int i;
    for(i=pos+1;i<ecs;++i) {
        if(coefs[i][pos]>eps||coefs[i][pos]<-eps) {
            change(i,pos);
            return 1;
        }
    }
    return 0;
}

void sub(int p1,int p2,int pos) {
    int i;
    double k;
    for(k=coefs[p1][pos]/coefs[p2][pos],i=pos;i<=unks;++i) {
        coefs[p1][i]-=k*coefs[p2][i];
    }
}

void adv(int pos) {
    int i;
    for(i=pos+1;i<ecs;++i) {
        sub(i,pos,pos);
    }
}

void go() {
    int i;
    for(i=0;i<unks;++i) {
        if(coefs[i][i]>=-eps&&coefs[i][i]<=eps) {
            if(!changeSuccess(i)) {
                continue;
            }
        }
        adv(i);
    }
}

void retreat(int pos) {
    int i;
    coefs[pos][unks]/=coefs[pos][pos];
    coefs[pos][pos]=1;
    for(i=0;i<pos;++i) {
        coefs[i][unks]-=coefs[i][pos]*coefs[pos][unks];
        coefs[i][pos]=0;
    }
}

void goBack() {
    int i;
    for(i=unks-1;i>=0;--i) {
        retreat(i);
    }
}

void solve() {
    go();
    if(compatibility) {
        goBack();
    }
}

int ver() {
    int i;
    for(i=unks;i<ecs;++i) {
        if(coefs[i][unks]>eps||coefs[i][unks]<-eps) {
            return 0;
        }
    }
    return 1;
}

void show() {
    int i;
    for(i=0;i<unks;++i) {
        if(coefs[i][i]>eps||coefs[i][i]<-eps) {
            printf("%.10lf ",coefs[i][unks]);
        }
        else {
            printf("0 ");
        }
    }
}

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

void display() {
    if(compatibility&&ver()) {
        show();
    }
    else {
        error();
    }
}

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