Cod sursa(job #3192366)

Utilizator tibinyteCozma Tiberiu-Stefan tibinyte Data 12 ianuarie 2024 13:41:31
Problema Algoritmul lui Gauss Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>

#define cin fin
#define cout fout

using namespace std;

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

const long double eps = 1e-15;

void gauss(int n, int m, vector<vector<long double>> a, vector<long double> &ans)
{
	vector<int> wh(m + 1);
	for (int row = 1, col = 1; row <= n && col <= m; ++col)
	{
		int qui = row;
		for (int i = row; i <= n; ++i)
		{
			if (abs(a[i][col]) > abs(a[qui][col]))
			{
				qui = i;
			}
		}
		if (abs(a[qui][col]) < eps)
		{
			continue;
		}
		swap(a[row], a[qui]);
		wh[col] = row;
		long double clown = a[row][col];
		for (int i = col; i <= m + 1; ++i)
		{
			a[row][i] /= clown;
		}
		for (int i = 1; i <= n; ++i)
		{
			if (i != row)
			{
				long double c = a[i][col];
				for (int j = col; j <= m + 1; ++j)
				{
					a[i][j] -= c * a[row][j];
				}
			}
		}
		++row;
	}
	ans = vector<long double>(m + 1);
	for (int i = 1; i <= m; ++i)
	{
		if (wh[i])
		{
			ans[i] = a[wh[i]][m + 1];
		}
	}
}

int32_t main()
{
	cin.tie(nullptr)->sync_with_stdio(false);
	int n, m;
	cin >> n >> m;
	vector<vector<long double>> a(n + 1, vector<long double>(m + 2));
	for (int i = 1; i <= n; ++i)
	{
		for (int j = 1; j <= m + 1; ++j)
		{
			cin >> a[i][j];
		}
	}
	vector<long double> ans;
	gauss(n, m, a, ans);
	for (int i = 1; i <= m; ++i)
	{
		cout << fixed << setprecision(10) << ans[i] << ' ';
	}
}