Cod sursa(job #3156364)

Utilizator andrei_C1Andrei Chertes andrei_C1 Data 11 octombrie 2023 12:17:56
Problema Algoritmul lui Gauss Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>

using ld = long double;
using namespace std;

ifstream fin("gauss.in");
ofstream fout("gauss.out");

const ld kEps = 1e-10;

int main() {
	int n, m;
	fin >> n >> m;
	vector<vector<ld>> a(n);
	for(int i = 0; i < n; i++) {
		a[i] = vector<ld>(m + 1);
		for(int j = 0; j <= m; j++) {
			fin >> a[i][j];
		}
	}
	vector<ld> x(m);
	vector<int> pos(m, -1);
	for(int col = 0, row = 0; col < m && row < n; col++) {
		int pivot = row;
		for(int i = pivot; i < n; i++) {
			if(abs(a[i][col]) > abs(a[pivot][col])) {
				pivot = i;
			}
		}
		if(abs(a[pivot][col]) <= kEps) {
			continue;
		}
		a[row].swap(a[pivot]);
		pos[col] = row;
		for(int i = 0; i < n; i++) if(i != row) {
			ld coef = a[i][col] / a[row][col];
			for(int j = 0; j <= m; j++) {
				a[i][j] -= a[row][j] * coef;
			}
		}
		row++;
	}

	for(int col = 0; col < m; col++) {
		if(pos[col] != -1) {
			x[col] = a[pos[col]][m] / a[pos[col]][col];
		}
	}

	for(int row = 0; row < n; row++) {
		ld sum = 0;
		for(int col = 0; col < m; col++) {
			sum += x[col] * a[row][col];
		}
		if(abs(sum - a[row][m]) > kEps) {
			fout << "Imposibil\n";
			return 0;
		}
	}
	for(int col = 0; col < m; col++) {
		fout << fixed << setprecision(12) << x[col] << " ";
	}
	fout << '\n';

	return 0;
}