Pagini recente » Cod sursa (job #2071503) | Cod sursa (job #2012234) | Cod sursa (job #2012970) | Cod sursa (job #2101767) | Cod sursa (job #1040015)
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define MAX_N 301
#define MAX_M 310
#define eps 0.0000001
using namespace std;
int n,m;
double coeff[MAX_N][MAX_M];
double variables[MAX_N];
int p[MAX_M];
int isSuccessful = 1;
double abs(double a){
if (a > 0.0){
return a;
} else {
return -1.0 * a;
}
}
int zero(double a){
if (abs(a) <= eps){
return 1;
} else {
return 0;
}
}
int obtainNonNullIndex(int i, int j){
for (int r=i; r<n; r++){
if (!zero(coeff[r][j])){
return r;
}
}
return -1;
}
void swapEquations(int eq1, int eq2){
double swapp;
for (int j = 0; j<m+1; j++){
swapp = coeff[eq1][j];
coeff[eq1][j] = coeff[eq2][j];
coeff[eq2][j] = swapp;
}
}
void divideEquationBy(int eq, double divisor){
for (int i=0; i<m+1; i++){
coeff[eq][i] = coeff[eq][i]/divisor;
}
}
int consistentRemainingEquations(int i){
for (int r=i; r<n; r++){
if (! zero(coeff[r][m])){
return 0;
}
}
return 1;
}
int main()
{
freopen("gauss.in", "r", stdin);
freopen("gauss.out", "w", stdout);
scanf("%d %d", &n, &m);
int number;
for (int i=0; i<n; i++){
for (int j=0; j<(m+1); j++){
scanf("%d", &number);
coeff[i][j] = (double)number;
}
}
int j=0;
int i=0;
for (i=0; i<n && j<m; i++){
int nonNullIndex = obtainNonNullIndex(i, j);
if (nonNullIndex != -1){
if (nonNullIndex != i){
swapEquations(i, nonNullIndex);
}
divideEquationBy(i, coeff[i][j]);
//now coeff[i][j] should be 1
int r = i+1;
while (r<n){
if (!zero(coeff[r][j])){
//we should eliminate coeff[r][j] a.i. we should make it 0
double multFactor = coeff[r][j] / (-1.0);
for (int ss=j; ss<m+1; ss++){
coeff[r][ss] = coeff[r][ss] + coeff[i][ss]*multFactor;
}
}
r++;
}
}
j++;
}
// cases: 1) we have more equations than variables (n> m)
// ==-> need to check if the remaining equations are "0" (the sistem is compatible)
// 2) more variables than equations. In this case suppose that the remaining variables are 0.
if (n > m) {
if (!consistentRemainingEquations(i)){
printf("Imposibil");
isSuccessful = 0;
}
}
j--;
i--;
if (isSuccessful){
while (i >= 0){
// actually i == j
if (zero(coeff[i][j])){
if (!zero(coeff[i][m])){
printf("Imposibil");
isSuccessful = 0;
break;
}
} else {
int r = j+1;
double partial = 0.0;
while (r<m){
partial += coeff[i][r]*variables[r];
r++;
}
variables[j] =coeff[i][m] - partial;
}
i--;
j--;
}
}
if (isSuccessful){
for (int i=0; i<m; i++){
printf("%lf ", variables[i]);
}
}
return 0;
}