Cod sursa(job #2639467)

Utilizator OvidRata Ovidiu Ovid Data 2 august 2020 12:00:54
Problema Algoritmul lui Gauss Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.13 kb
#include<bits/stdc++.h>
using namespace std;
#define INIT  ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
#define mp make_pair
#define pb push_back
#define ft first
#define sc second
#define ll long long
#define pii pair<int, int>
#define count_bits __builtin_popcount
#define int ll

ifstream fin("gauss.in"); ofstream fout("gauss.out");
#define cin fin
#define cout fout

int t, n, m, k;
int a[310][310];
double mat[310][310];






bool check(){

double sol[310];
for(int i=1; i<=(m); i++){
    sol[i]=mat[i][m+1];
}

for(int i=1; i<=n; i++){
    double fin=0;
    for(int j=1; j<=(m); j++){
        fin=fin+(sol[j]*a[i][j]);
    }
    int dif=fin-a[i][m+1];
    if(dif<0){dif=-dif;}
    if(dif>=(0.002) ){return false;}
}



return true;
}




bool gauss(){
//normalize();


for(int i=1; i<=n; i++){
    for(int j=1; j<=(m+1); j++){
        mat[i][j]=a[i][j];
    }
}

int i=1, j=1;


while( (i<=n) && (j<=m) ){

    while(mat[i][j]==0){
        int mx=-2000, mxr=0;
        for(int r=1; r<=n; r++){
            if(mat[r][j]>0){
                if(mat[r][j]>mx){
                    mx=mat[r][j];
                    mxr=r;
                }
            }
        }
        for(int c=1; c<=(m+1); c++){
            mat[i][c]+=mat[mxr][c];
        }
    }

    if(mat[i][j]==((double)0) ){j++; continue;}


    double d=mat[i][j];
    for(int c=1; c<=(m+1); c++ ){
        mat[i][c]=(mat[i][c]/d);
    }
    for(int r=1; r<=n; r++){
            if(r==i){continue;}
        double mul=(-mat[r][j]);
        for(int c=1; c<=(m+1); c++){
            mat[r][c]=mat[r][c]+(mul*mat[i][c]);
        }
    }

    i++; j++;

}





return check();



}





int32_t main(){
INIT
cin>>n>>m;
for(int i=1; i<=n; i++){
    for(int j=1; j<=(m+1); j++){
        cin>>a[i][j];
    }
}


if( (gauss())==true ){
    for(int i=1; i<=(m); i++){
        cout<<fixed<<setprecision(12)<<mat[i][m+1]<<" ";
    }
}
else{
cout<<"Imposibil";
}









return 0;
}