Pagini recente » Cod sursa (job #1993081) | Cod sursa (job #141610) | Cod sursa (job #84086) | Cod sursa (job #2611476) | Cod sursa (job #3233301)
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
#include <iomanip>
using namespace std;
const double EPS = 1e-10;
void gaussJordan(vector<vector<double>> &matrix, int n, int m) {
int i, j, k, col;
for (i = 0, col = 0; i < n && col < m; ++i, ++col) {
// Find the pivot row
int pivot = i;
for (j = i + 1; j < n; ++j) {
if (fabs(matrix[j][col]) > fabs(matrix[pivot][col])) {
pivot = j;
}
}
if (fabs(matrix[pivot][col]) < EPS) {
--i;
continue;
}
// Swap the current row with the pivot row
swap(matrix[i], matrix[pivot]);
// Normalize the pivot row
double pivotValue = matrix[i][col];
for (k = col; k <= m; ++k) {
matrix[i][k] /= pivotValue;
}
// Eliminate the current column in all other rows
for (j = 0; j < n; ++j) {
if (j != i) {
double factor = matrix[j][col];
for (k = col; k <= m; ++k) {
matrix[j][k] -= factor * matrix[i][k];
}
}
}
}
}
int main() {
ifstream infile("gauss.in");
ofstream outfile("gauss.out");
int n, m;
infile >> n >> m;
vector<vector<double>> matrix(n, vector<double>(m + 1));
for (int i = 0; i < n; ++i) {
for (int j = 0; j <= m; ++j) {
infile >> matrix[i][j];
}
}
gaussJordan(matrix, n, m);
// Check for inconsistency or infinite solutions
bool infiniteSolutions = false;
vector<double> solution(m, 0.0);
for (int i = 0; i < n; ++i) {
bool allZero = true;
for (int j = 0; j < m; ++j) {
if (fabs(matrix[i][j]) > EPS) {
allZero = false;
break;
}
}
if (allZero && fabs(matrix[i][m]) > EPS) {
outfile << "Imposibil" << endl;
return 0;
}
if (allZero && fabs(matrix[i][m]) < EPS) {
infiniteSolutions = true;
}
}
if (infiniteSolutions) {
outfile << "Imposibil" << endl;
return 0;
}
// Extract the solution
for (int i = 0; i < m; ++i) {
solution[i] = matrix[i][m];
}
// Print the solution
outfile << fixed << setprecision(8);
for (int i = 0; i < m; ++i) {
outfile << solution[i] << " ";
}
outfile << endl;
infile.close();
outfile.close();
return 0;
}