Cod sursa(job #2209752)

Utilizator TooHappyMarchitan Teodor TooHappy Data 4 iunie 2018 16:57:13
Problema Algoritmul lui Gauss Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.24 kb
#include <bits/stdc++.h>
using namespace std;
      
ifstream in("gauss.in");
ofstream out("gauss.out");

vector< vector< double > > sist;
vector< double > solutii;

int main() {
    ios::sync_with_stdio(false); in.tie(0); out.tie(0);
    
    int nrEcuatii, nrNecunoscute; in >> nrEcuatii >> nrNecunoscute;

    sist.resize(nrEcuatii, vector< double >(nrNecunoscute + 1)); solutii.resize(nrNecunoscute);
    for(int i = 0; i < nrEcuatii; ++i) {
        for(int j = 0; j < nrNecunoscute + 1; ++j) {
            in >> sist[i][j];
        }
    }

    for(int i = 0; i < nrEcuatii; ++i) {
        bool goOn = false;

        if(sist[i][i] == 0.0) {
            for(int j = i + 1; j < nrEcuatii; ++j) {
                if(sist[j][i] == 0.0) {
                    continue;
                }

                swap(sist[i], sist[j]);
                break;
            }
            goOn = true;
        }

        if(goOn == true) {
            continue;
        }

        for(int j = i + 1; j < nrEcuatii; ++j) {
            if(sist[j][i] == 0.0) {
                continue;
            }

            double temp = sist[i][i] / sist[j][i];
            if(sist[i][i] *  sist[j][i] < 0) {
                temp = -temp;
            }

            for(int k = i; k < nrNecunoscute + 1; ++k) {
                sist[j][k] = sist[i][k] + temp * sist[j][k];
            }
        }
    }
    
    bool imposibil = true;
    for(int j = 0; j < nrNecunoscute && imposibil; ++j) {
        if(sist[nrEcuatii - 1][j] != 0.0) {
            imposibil = false;
        }
    }

    if(imposibil) {
        out << "Imposibil\n";
        exit(0);
    }

    // Ramane de scos necunoscutele de jos in sus.
    
    solutii[nrNecunoscute - 1] = sist[nrEcuatii - 1][nrNecunoscute] / sist[nrEcuatii - 1][nrNecunoscute - 1];

    for(int i = nrEcuatii - 2; i >= 0; --i) {
        double sol = sist[i][nrNecunoscute];
        for(int j = nrNecunoscute - 1; j > i; --j) {
            sol = sol - sist[i][j] * solutii[j];
        }

        if(sist[i][i] != 0.0) {
            sol /= sist[i][i];
        }
        solutii[i] = sol;
    }

    for(int i = 0; i < nrNecunoscute; ++i) {
        out << fixed << setprecision(8) << solutii[i] << " ";
    }
    out << "\n";

    in.close(); out.close();
      
    return 0;
}