Cod sursa(job #928674)

Utilizator fhandreiAndrei Hareza fhandrei Data 26 martie 2013 16:58:27
Problema Algoritmul lui Gauss Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
// Include
#include <fstream>
#include <iomanip>
using namespace std;
 
// Constante
const int sz = 302;
const double ERROR = 1e-7;
 
// Functii
void SWAP(double* a, double* b);
template<class T> T ABS(T x);
 
// Variabile
ifstream in("gauss.in");
ofstream out("gauss.out");
 
int lines, columns, allColumns;
double SYSTEM[sz][sz];
double X[sz];
 
// Main
int main()
{
	out << fixed << setprecision(8);
	
	in >> lines >> columns;
	allColumns = columns+1;
	for(int i=1 ; i<=lines ; ++i)
		for(int j=1 ; j<=allColumns ; ++j)
			in >> SYSTEM[i][j];
	
	int i=1, j=1;
	
	while(i<=lines && j<=columns) // i-ecuatie, j-necunoscuta
	{
		int eq;
		for(eq=i ; eq<=lines ; ++eq)
		{
			//if(SYSTEM[eq][j])
			if(ABS(SYSTEM[eq][j]) > ERROR)
				break;
		}
		
		if(eq == lines+1)
		{
			++j;
			continue;
		}
		
		if(eq != i)
			SWAP(SYSTEM[i], SYSTEM[eq]);
		
		for(int pos=j+1 ; pos<=allColumns ; ++pos)
			SYSTEM[i][pos] /= SYSTEM[i][j];
		SYSTEM[i][j] = 1;
		
		for(eq=i+1 ; eq<=lines ; ++eq)
		{
			for(int pos=j+1 ; pos<=allColumns ; ++pos)
				SYSTEM[eq][pos] -= SYSTEM[eq][j] * SYSTEM[i][pos];
			SYSTEM[eq][j] = 0;
		}
		
		++i, ++j;
	}
	
	for(int i=lines ; i ; --i)
	{
		for(int pos=1 ; pos<=allColumns ; ++pos)
		{
			//if(!SYSTEM[i][pos])
			if(ABS(SYSTEM[i][pos]) < ERROR)
				continue;	
			
			if(pos == allColumns) // rezultatul
			{
				out << "Imposibil" << '\n';
				in.close();
				out.close();
				return 0;
			}
			
			X[pos] = SYSTEM[i][allColumns];
			
			for(int j=pos+1 ; j<=columns ; ++j)
				X[pos] -= X[j]*SYSTEM[i][j];
			
			break;
		}
	}
	
	for(int i=1 ; i<=columns ; ++i)
		out << X[i] << ' ';
	out << '\n';
	
	in.close();
	out.close();
	return 0;
}
 
void SWAP(double* a, double* b)
{
	for(int i=1 ; i<=allColumns ; ++i)
		swap(a[i], b[i]);
}
 
template<class T> T ABS(T x)
{   return x<0? -x:x;	}