Cod sursa(job #810745)

Utilizator rvnzphrvnzph rvnzph Data 10 noiembrie 2012 22:09:43
Problema Algoritmul lui Gauss Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <stdio.h>
#include <iostream>
#include <string.h>

#define MLen 301
#define NLen 302

using namespace std;

double a[MLen][NLen];

double sol[NLen];

inline void swap(double &a,double &b)
{
	double aux=a;
	a=b;
	b=aux;
}

int main()
{
	freopen("gauss.in","r",stdin);
	freopen("gauss.out","w",stdout);

	int M,N;

	cin>>M>>N;
	++N;

	for(int i=1;i<=M;++i)
		for(int j=1;j<=N;++j)
			cin>>a[i][j];

	int row,col;
	for(row=1,col=1;row<=M&&col<N;)
	{
		if(a[row][col]==0)
		{
			int ok=0;

			for(int x=row+1;x<=M;++x)
				if(a[x][col])
				{
					ok=x;
					break;
				}

			if(ok)
				for(int y=col;y<=N;++y) swap(a[row][y],a[ok][y]);
			else
			{
				++row;
				continue;
			}
		}

		for(int y=col+1;y<=N;++y) a[row][y]/=a[row][col];
		a[row][col]=1;

		for(int x=row+1;x<=M;++x)
			if(a[x][col])
			{
				for(int y=col+1;y<=N;++y)
					a[x][y]-=a[x][col]*a[row][y];
				a[x][col]=0;
			}

		++row;
		++col;
	}

	if(col<N)
	{
		cout<<"Imposibil\n";
		return 0;
	}

	memset(sol,0,sizeof(sol));

	--col;
	--row;
	for(;row>0&&col>0;)
	{
		if(a[row][col]==0)
		{
			--row;
			continue;
		}

		while(a[row][col-1]) --col;

		for(int y=col+1;y<N;++y)
			sol[col]+=a[row][y]*sol[y];

		sol[col]*=-1;
		col[sol]+=a[row][N];

		--col;
		--row;
	}

	for(int i=1;i<N;++i)
		printf("%.10lf ",sol[i]);
	cout<<'\n';

	return 0;
}