Pagini recente » Cod sursa (job #659207) | Cod sursa (job #829269) | Cod sursa (job #3140215) | Cod sursa (job #465101) | Cod sursa (job #2705104)
#include <bits/stdc++.h>
#define ll long long
#define EPS 1e-10
using namespace std;
ifstream in("gauss.in");
ofstream out("gauss.out");
int n, m;
vector<vector<double> > a;
vector<double> substitutie_descendenta(vector<vector<double> > a) {
int n = a.size();
vector<double> sol(n, 0);
sol[n - 1] = a[n - 1][n] / a[n - 1][n - 1];
for (int k = n - 2; k >= 0; k--) {
double sum = 0;
for (int j = k + 1; j < n; j++)
sum += a[k][j] * sol[j];
sol[k] = (a[k][n] - sum) / a[k][k];
}
return sol;
}
vector<double> gauss_pivotare_totala(vector<vector<double> > a) {
int n = a.size();
vector<int> perm(n, 0);
for (int i = 0; i < n; i++) {
perm[i] = i;
}
for (int k = 0; k < n; k++) {
int row = 0, col = 0;
double mx = 0;
for (int i = k; i < n; i++) {
for (int j = k; j < n; j++) {
if (abs(a[i][j]) > mx) {
mx = abs(a[i][j]);
row = i;
col = j;
}
}
}
if (abs(mx) < EPS) {
throw "Imposibil";
}
if (k != row) {
for (int j = 0; j <= n; j++) {
swap(a[k][j], a[row][j]);
}
}
if (k != col) {
for (int i = 0; i < n; i++) {
swap(a[i][k], a[i][col]);
}
swap(perm[k], perm[col]);
}
for (int i = k + 1; i < n; i++) {
double ratio = a[i][k] / a[k][k];
for (int j = k; j <= n; j++) {
a[i][j] -= ratio * a[k][j];
}
}
}
auto aux = substitutie_descendenta(a);
auto sol = aux;
for (int i = 0; i < n; i++) {
sol[perm[i]] = aux[i];
}
return sol;
}
int main() {
in >> n >> m;
a = vector<vector<double> >(n, vector<double>(m + 1, 0));
for (int i = 0; i < n; i++) {
for (int j = 0; j <= m; j++) {
in >> a[i][j];
}
}
if (n != m) {
return cout << "Imposibil", 0;
}
try {
auto sol = gauss_pivotare_totala(a);
for (auto it : sol) {
out << fixed << setprecision(10) << it << ' ';
}
} catch (const char *msg) {
out << msg;
}
return 0;
}