Cod sursa(job #1911697)

Utilizator lflorin29Florin Laiu lflorin29 Data 7 martie 2017 21:27:34
Problema Algoritmul lui Gauss Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <bits/stdc++.h>

using namespace std;

const int nMax = 302;
const double eps = 1e-10;

int n, m;
double a[nMax][nMax];
double val[nMax];

bool eq(double x, double y) {
	return abs(x - y) < eps;
}

int main() {
	ifstream cin("gauss.in");
	ofstream cout("gauss.out");
	cin >> n >> m;

	for (int i = 1; i <= n; ++i)
		for (int j = 1; j <= m + 1; ++j)
			cin >> a[i][j];

	for (int i = 1, j = 1; i <= n and j <= m;) {
		int pos = -1;

		for (int k = i; k <= n; ++k)
			if (!eq(a[k][j], 0))
				pos = k;

		if (pos == -1) {
			++j;
			continue;
		}

		swap(a[pos], a[i]);

		for (int k = i + 1; k <= n; ++k) {
			double mul = -a[k][j] / a[i][j];

			for (int c = j + 1; c <= m + 1; ++c) {
				a[k][c] += mul * a[i][c];
			}

			a[k][j] = 0;
		}

		++i;
		++j;
	}

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

		for (int j = 1; j <= m; ++j)
			if (!eq(a[i][j], 0))any = true;

		if (!any && !eq(a[i][m + 1], 0)) {
			cout << "Imposibil";
			return 0;
		}
	}

	for (int nec = m; nec >= 1; --nec) {
		val[nec] = 0;

		for (int j = n; j >= 1; --j) {
			if (!eq(a[j][nec], 0)) {
				val[nec] = a[j][m + 1];

				for (int k = nec + 1; k <= m; ++k) {
					val[nec] -= val[k] * a[j][k];
				}

				val[nec] /= a[j][nec];
				break;
			}
		}
	}

	cout << fixed << setprecision(10);

	for (int i = 1; i <= m; ++i)
		cout << val[i] << ' ';
}