Cod sursa(job #2736263)

Utilizator lucametehauDart Monkey lucametehau Data 3 aprilie 2021 12:14:57
Problema Algoritmul lui Gauss Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <fstream>
#include <cmath>
#include <iomanip>

using namespace std;

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

const long double EPS = 1e-9;

int n, m;

long double v[305][305], ans[305];
int pos[305];

int main() {
  cin >> n >> m;
  for(int i = 1; i <= n; i++) {
    for(int j = 1; j <= m + 1; j++)
      cin >> v[i][j];
  }
  int lin = 1;
  for(int j = 1; j <= m; j++) {
    int ind = lin;
    for(int i = lin + 1; i <= n; i++) {
      if(abs(v[i][j]) > abs(v[ind][j]))
        ind = i;
    }

    if(abs(v[ind][j]) < EPS)
      continue;

    swap(v[lin], v[ind]);
    pos[j] = lin;

    for(int i = 1; i <= n; i++) {
      if(i != lin) {
        long double ct = v[i][j] / v[lin][j];
        for(int k = j; k <= m + 1; k++)
          v[i][k] -= v[lin][k] * ct;
      }
    }

    lin++;
  }
  for(int j = 1; j <= m; j++) {
    if(pos[j])
      ans[j] = v[pos[j]][m + 1] / v[pos[j]][j];

    //cout << "x[" << j << "] = " << ans[j] << "\n";
  }

  for(int i = 1; i <= n; i++) {
    long double s = 0;
    for(int j = 1; j <= m; j++)
      s += ans[j] * v[i][j];

    //cout << s << " is what i got, " << v[i][m + 1] << " was the answer\n";

    if(abs(s - v[i][m + 1]) > EPS) {
      cout << "Imposibil";
      return 0;
    }
  }
  cout << fixed << setprecision(10);
  for(int j = 1; j <= m; j++)
    cout << ans[j] << " ";
  return 0;
}