Cod sursa(job #2337949)

Utilizator Alex18maiAlex Enache Alex18mai Data 6 februarie 2019 20:44:53
Problema Algoritmul lui Gauss Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.12 kb
//ALEX ENACHE

#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <unordered_map>
#include <time.h>
#include <iomanip>
#include <deque>
#include <math.h>
#include <cmath>
#include <assert.h>
#include <stack>
#include <bitset>

using namespace std;

//#include <iostream>
#include <fstream>
ifstream cin ("gauss.in");ofstream cout ("gauss.out");

int n , m;
long double v[310][310];
int sp[310][310];
long double ans[310];
const long double eps = 0.00000000001;

bool exist (long double nr){
    if (nr <= eps && nr >= -eps){
        return false;
    }
    return true;
}

void scade (int a , int b , long double cost){
    for (int j=1; j<=m+1; j++){
        v[a][j] -= v[b][j] * cost;
    }
}

int main() {

    //freopen("input", "r", stdin);freopen("output", "w", stdout);

    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    cin>>n>>m;

    for (int i=1; i<=n; i++){
        for (int j=1; j<=m+1; j++){
            int nr;
            cin>>nr;
            v[i][j] = nr;
        }
    }

    for (int j=1; j<=m; j++){
        if (j > n){
            continue;
        }
        int pnt = j;
        while (pnt <= n && !exist(v[pnt][j])){
            pnt++;
        }
        if (pnt == n+1){
            continue;
        }
        swap(v[j] , v[pnt]);
        for (int i=j+1; i<=n; i++){
            if (exist(v[i][j])){
                scade(i , j , v[i][j] / v[j][j]);
            }
        }
    }

    for (int i=1; i<=n; i++){
        for (int j=1; j<=m; j++){
            //cout<<v[i][j]<<" ";
            sp[i][j] = sp[i][j-1] + exist(v[i][j]);
        }
        //cout<<'\n';
    }

    for (int j=m; j>=1; j--){
        for (int i=1; i<=n; i++){
            if (sp[i][j] == 1){
                ans[j] = v[i][m+1] / v[i][j];
            }
        }
        for (int i=1; i<=n; i++){
            v[i][m+1] -= ans[j] * v[i][j];
        }
    }

    for (int i=1; i<=n; i++){
        if (exist(v[i][m+1])){
            cout<<"Imposibil"<<'\n';
            return 0;
        }
    }

    for (int j=1; j<=m; j++){
        cout<<setprecision(15)<<fixed<<ans[j]<<" ";
    }


    return 0;
}