Cod sursa(job #2553503)

Utilizator Briana_NeaguNeagu Briana Briana_Neagu Data 22 februarie 2020 07:56:37
Problema Algoritmul lui Gauss Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.9 kb
#include <bits/stdc++.h>
#define eps 0.0000001

using namespace std;

ifstream f("gauss.in");
ofstream g("gauss.out");


bool isZero(double x)
{
    return !(x < -eps || x > eps);
}

int main()
{
   int n, m;
   f >> n >> m;
   vector <vector <double> > matrix(n + 1, vector <double> (m + 2, 0));
   for (int i = 1; i <= n; ++ i)
       for (int j = 1; j <= m + 1; ++ j)
           f >> matrix[i][j];

   int setLine = 1, setCol = 1;
   while (setLine <= n && setCol <= m)
   {
       int notZeroLine = setLine;
       while (notZeroLine <= n && isZero(matrix[notZeroLine][setCol]))
           notZeroLine ++;
       if (notZeroLine > n)
       {
           setCol ++;
           continue;
       }
       if (notZeroLine != setLine)
           for (int col = 1; col <= m + 1; ++ col)
               swap(matrix[setLine][col], matrix[notZeroLine][col]);

       for (int col = setLine + 1; col <= m + 1; ++ col)
           matrix[setLine][col] /= matrix[setLine][setCol];
       matrix[setLine][setCol] = 1;
       for (int line = setLine + 1; line <= n; ++ line)
       {
           for (int col = setCol + 1; col <= m + 1; ++ col)
               matrix[line][col] =  matrix[line][col] - (matrix[line][setCol] * matrix[setLine][col]);
           matrix[line][setCol] = 0;
       }

       setLine ++;
       setCol ++;
   }
   vector <double> ans(n + 1, 0);
   for (int line = n; line >= 1; -- line)
   {
       bool found = 0;
       for (int col = 1; col <= m; ++ col)
           if (!isZero(matrix[line][col]))
           {
               found = 1;
               ans[col] = matrix[line][m + 1];
               for (int next = col + 1; next <= m; ++ next)
                   ans[col] -= matrix[line][next] * ans[next];
              break;
           }
       if (!found)
       {
           g << "Imposibil";
           return 0;
       }

   }
   for (int i = 1; i <= m; ++ i)
       g << setprecision(11) << fixed << ans[i] << " ";

}