Cod sursa(job #2639389)

Utilizator OvidRata Ovidiu Ovid Data 1 august 2020 20:43:21
Problema Algoritmul lui Gauss Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.07 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];

void pivot(int dg){
int mx=-2000, mxr=0;
for(int i=1; i<=n; i++){
    if(a[i][dg]==a[dg][dg]){
        if(a[i][dg]>mx){
            mx=a[i][dg], mxr=i;
        }
    }
}
for(int i=1; i<=(m+1); i++){
    a[dg][i]+=a[mxr][i];
}
}

void normalize(){
for(int i=1; i<=n; i++){
    for(int j=1; j<=m; j++){
        if( (a[i][j]==0) && (i==j) ){
            pivot(i);
        }
    }
}
}


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.001) ){return false;}
}



return true;
}




bool gauss(){
normalize();

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

for(int k=1; k<=m; k++){
    double d=mat[k][k];
    for(int j=1; j<=(m+1); j++){
        mat[k][j]=mat[k][j]/d;
    }
    for(int i=1; i<=n; i++){
        if(i==k){continue;}
        double mul=-mat[i][k];
        for(int j=1; j<=(m+1); j++){
            mat[i][j]=mat[i][j]+(mul*mat[k][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;
}