Cod sursa(job #1759705)

Utilizator BrandonChris Luntraru Brandon Data 19 septembrie 2016 18:41:49
Problema Algoritmul lui Gauss Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include <fstream>
#include <iomanip>

using namespace std;

ifstream cin ("gauss.in");
ofstream cout ("gauss.out");

const int MaxN = 305;
const double Eps = 1e-10;

int n, m;
double mat[MaxN][MaxN];

inline void LineSwap(double v1[MaxN], double v2[MaxN]) {
  for (int i = 1; i <= m + 1; ++i) {
    swap(v1[i], v2[i]);
  }
}

inline void AddLine(double v1[MaxN], double v2[MaxN], double coef) {
  for (int i = 1; i <= m + 1; ++i) {
    v2[i] += v1[i] * coef;
  }
}

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

  int CurrLin = 1;
  for (int CurrCol = 1; CurrCol <= m; ++CurrCol) {
    if (CurrLin > n) {
      break;
    }

    if (!mat[CurrLin][CurrCol]) {
      for (int i = CurrLin + 1; i <= n; ++i) {
        if (mat[i][CurrCol]) {
          LineSwap(mat[i], mat[CurrLin]);
          break;
        }
      }

      if (!mat[CurrLin][CurrCol]) { ///CurrLin does not advance, column is "removed"
        continue;
      }
    }

    for (int i = 1; i <= n; ++i) { ///Get all other lines on column to 0
      if (i == CurrLin) {
        continue;
      }

      AddLine(mat[CurrLin], mat[i], -(mat[i][CurrCol] / mat[CurrLin][CurrCol]));
    }

    ++CurrLin;
  }

  for (int i = 1; i <= n; ++i) {
    bool LineExists = false;

    for (int j = 1; j <= m; ++j) {
      if (mat[i][j] < -Eps || mat[i][j] > Eps) {
        LineExists = true;
        break;
      }
    }

    if (!LineExists and mat[i][m + 1]) {
      cout << "Imposibil\n";
      return 0;
    }
  }

  CurrLin = 1;
  for (int j = 1; j <= m; ++j) {
    double ans = 0;
    if (mat[CurrLin][j]) {
      ans = mat[CurrLin][m + 1] / mat[CurrLin][j];
      ++CurrLin;
    }
    cout << fixed << setprecision(10) << ans << ' ';
  }
  return 0;
}