Cod sursa(job #622993)

Utilizator the@EyE@Postavaru Stefan the@EyE@ Data 18 octombrie 2011 20:40:41
Problema Algoritmul lui Gauss Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include<stdio.h>
#include <stdlib.h>
#define INF 500
#define error 0.001


int n,m;
double mat[INF][INF],ras[INF];
bool ok=true;

void swap(int l1,int l2)
{
	double aux;
	for(int i=0;i<=m;i++)
	{
		aux=mat[l1][i];
		mat[l1][i]=mat[l2][i];
		mat[l2][i]=aux;
	}
}

void add(int l1,int l2)
{
	for(int i=0;i<=m;i++)
		mat[l2][i]+=mat[l1][i];
}

int main()
{
	freopen("gauss.in","r",stdin);
	freopen("gauss.out","w",stdout);
	scanf("%d %d\n",&n,&m);//n-ecuatii m-necunoscute
	
	//if(n<m)ok=false;
	//else
	int ind=0;
		for(int i=0;i<m;i++)
			for(int j=0;j<=m;j++)
				scanf("%lf",&mat[i][j]);
			
		
		double coef;
        while(ind<n-1)
        {
			if(abs(mat[ind][ind])<error)
				for(int i=ind+1;i<m;i++)if(mat[i][ind]!=0)swap(i,ind);
			if(abs(mat[ind][ind])<error)
			{
				ok=false;
				break;
			}
			
			for(int i=ind;i<m;i++)
			{
				if(abs(mat[i][ind])>error)
				{
				if(i==ind)coef=1/mat[i][ind];
				else coef=-1*1/mat[i][ind];
				}
				else coef=0;
				for(int j=ind;j<=m;j++)mat[i][j]*=coef;
			}
			
			for(int i=ind+1;i<m;i++)add(ind,i);		
            ind++;			
		}
		
	while(ind<m-1&&mat[n-1][ind]==0)ind++;
	if(ind!=m-2)ok=false;
		if(ok)
		{
        ras[m-1]=mat[m-1][m]/mat[m-1][m-1];
        for(int i=m-2;i>-1;i--)
		{
			double s=0;
			for(int j=i+1;j<m;j++)s+=mat[i][j]*ras[j];
			ras[i]=mat[i][m]-s;
		}
		
		for(int i=0;i<m;i++) printf("%lf ",ras[i]);
		}
		else  printf("Imposibil\n");
	
}