Cod sursa(job #743767)

Utilizator theep0Cruceru Radu theep0 Data 5 mai 2012 20:28:58
Problema Algoritmul lui Gauss Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <stdio.h>
#include <stdlib.h>

#define nrel 303
#define err 0.0000002

int main()
{
	freopen("gauss.in","r",stdin);
	freopen("gauss.out","w",stdout);
	double mat[nrel][nrel], x[nrel],tmp,ratio;
	int i,j,u,v,N,M;
	scanf("%d %d",&N,&M);
	for(i=1;i<=N;i++)
	{
		for(j=1;j<=M + 1;j++)
		{
			scanf("%lg",&mat[i][j]);
		}
	}
	
	//gauss define
	i=1;j=1;
	while(i<=N && j<=M)
	{
		
		for(u=i;u<=N;u++)
			if(mat[u][j] <= -err || mat[u][j] >= err ) break;
		
			
		if(u==N+1)
		{
			j++;continue;
		}
		
		if(u!=i)
		{
			for(v=1;v<=M+1;v++)
			{
				tmp = mat[u][v];
				mat[u][v] = mat[i][v];
				mat[i][v] = tmp;
			}
		}
		
		for(u=i+1;u<=N;u++)
		{
			ratio = mat[u][j]/mat[i][j];
			for(v=j;v<=M+1;v++)
			{
				mat[u][v] = mat[u][v] - ratio*mat[i][v];	
			}
		}
	i++;
	j++;			
	}
	
	/*for(i=1;i<=N;++i)
	{
		for(j=1;j<=M;++j)
		{
			printf("%lf ",mat[i][j]);
		}
		printf("\n");
	}*/
	for(i=N;i>=1;i--)
	{
		for(j=1;j<=M;++j)
		{
			if(mat[i][j] <= -err || mat[i][j] >= err)
			{
				//printf("%lf",mat[u][j])
				break;
			}
		}
		if(j==M+1)
		{
			printf("imposibil");
			return 0;
		}
		
		/*x[j] = mat[i][M+1]/mat[i][j];
		for(u=i;i>=1;--i)
		{
			mat[u][M+1] -= mat[u][j] * x[j];
		}*/
			if(mat[i][j] != 0)
			{
				tmp = mat[i][M+1];
				for(u=j+1;u<=M;u++)
				{
					tmp = tmp - mat[i][u]*x[u];
				}
				x[j] = tmp/mat[i][j];
				
			}
			//printf("%lg\n",x[j]);
		//}
		
	}
	
	/*
	for(i=1;i<=N;i++)
	{
		for(j=1;j<=M+1;j++)
		{
			printf("%lg ",mat[i][j]);
		}
		printf("\n");
	}
	printf("\n");*/
	for(i=1;i<=M;i++)
	{
		printf("%.8lf ",x[i]);
	}
	return 0;
}