Cod sursa(job #1410875)

Utilizator ericptsStavarache Petru Eric ericpts Data 31 martie 2015 12:26:41
Problema Algoritmul lui Gauss Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.04 kb
#include <fstream>
#include <iostream>
#include <iomanip>

using namespace std;

const int MAX_N = 300 + 1;
const int MAX_M = 300 + 2;

const double EPS = 1e-10;

int n, m;

double mat[MAX_N][MAX_M];

double sol[MAX_N];

void showMat() {
    for(int i = 1 ; i <= n ; ++i) {
        for(int j = 1 ; j <= m + 1 ; ++j) {
            cout << mat[i][j] << " ";
        }
        cout << "\n";
    }
    cout << "\n\n\n";
}

void mulLine(int i, double val) {
    for(int j = 1 ; j <= m + 1 ; ++j)
        mat[i][j] *= val;
}

void swapLine(int i, int k) {
    for(int j = 1 ; j <= m + 1 ; ++j)
        swap(mat[i][j], mat[k][j]);
}

void addLine(int i, int k, double coef) {
    for(int j = 1 ; j <= m + 1 ; ++j)
        mat[k][j] += mat[i][j] * coef;
}

double abs(double x) {
    if(x < 0)
        return -x;
    return x;
}

bool solve() {
    int l = 1, c = 1;
    while(c <= m && l <= n) {
        int i = l;
        while(i <= n && abs(mat[i][c]) <= EPS)
            ++i;

        if(i <= n) {
            swapLine(i, l);
            mulLine(l, 1 / mat[l][c]);

            for(int j = 1 ; j <= n ; ++j) {
                if(j == l)
                    continue;
                addLine(l, j, -mat[j][c]);
            }
        }
        ++c;
        ++l;
    }

    for(int i = 1 ; i <= n ; ++i) {
        bool found = 0;
        for(int j = 1 ; j <= m && !found ; ++j) {
            if(mat[i][j]) {
                sol[j] = mat[i][m + 1];
                found = 1;
            }
        }
        if(!found && abs(mat[i][m + 1]) > EPS)
            return 0;
    }
    return 1;
}

int main() {
    ifstream in("gauss.in");
    in >> n >> m;
    for(int i = 1 ; i <= n ; ++i) {
        for(int j = 1 ; j <= m + 1 ; ++j) {
            in >> mat[i][j];
        }
    }

    ofstream out("gauss.out");

    if(solve()) {
        for(int i = 1 ; i <= m ; ++i)
            out << fixed << setprecision(8) << sol[i] << " ";
        out << "\n";
    } else {
        out << "Imposibil\n";
    }
}