Cod sursa(job #2638413)

Utilizator segtreapMihnea Andreescu segtreap Data 28 iulie 2020 10:33:58
Problema Algoritmul lui Gauss Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <bits/stdc++.h>

using namespace std;

int main() {
  freopen ("gauss.in", "r", stdin);
  freopen ("gauss.out", "w", stdout);

  typedef long double ld;
  const ld EPS = 1e-14;

  int n, m;
  cin >> n >> m;
  vector<vector<ld>> a(n);
  vector<int> pos(n, -1);
  vector<ld> sol(m, 0);

  for (int i = 0; i < n; i++) {
    a[i].resize(m + 1);
    for (int j = 0; j < m + 1; j++) {
      cin >> a[i][j];
    }
  }
  for (int col = 0, row = 0; row < n && col < m; col++) {
    int row2 = row;
    for (int i = row + 1; i < n; i++) {
      if (fabs(a[i][col]) > fabs(a[row2][col])) {
        row2 = col;
      }
    }
    if (fabs(a[row2][col]) < EPS) {
      continue;
    }
    if (row != row2) {
      for (int j = col; j <= m; j++) {
        swap(a[row][j], a[row2][j]);
      }
    }
    pos[row] = col;
    for (int i = 0; i < n; i++) {
      if (i != row) {
        ld coef = -a[i][col] / a[row][col];
        for (int j = col; j <= m; j++) {
          a[i][j] += coef * a[row][j];
        }
      }
    }
    row++;
  }
  for (int i = 0; i < n; i++) {
    int j = pos[i];
    if (j == -1) {
      continue;
    }
    sol[j] = a[i][m] / a[i][j];
  }
  for (int i = 0; i < n; i++) {
    ld sum = 0;
    for (int j = 0; j < m; j++) {
      sum += a[i][j] * sol[j];
    }
    if (fabs(sum - a[i][m]) > EPS) {
      cout << "Imposibil\n";
      return 0;
    }
  }
  for (int i = 0; i < m; i++) {
    cout << fixed << setprecision(10) << sol[i] << " ";
  }
  cout << "\n";

  return 0;
}