其他分享
首页 > 其他分享> > luogu P2455 [SDOI2006]线性方程组

luogu P2455 [SDOI2006]线性方程组

作者:互联网

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>

using namespace std;

const int N=60;
const double eps=0.000001;
int n,flag[N];
double a[N][N],b[N][N];

void init()
{
	scanf("%d",&n);
	for (int i=1;i<=n;i++)
		for (int j=1;j<=n+1;j++)
			scanf("%lf",&a[i][j]);
	memcpy(b,a,sizeof(b));
}

void Gauss()
{
	int line=1;
	for (int i=1;i<=n;i++)
	{
		int Max=i;
		for (int j=i+1;j<=n;j++)
			if(fabs(a[j][line])>fabs(a[Max][line])) Max=j;
		for (int j=1;j<=n+1;j++)
			swap(a[Max][j],a[i][j]);
		while(fabs(a[i][line])<eps&&line<=n)
		{
			line++;
			int Max=i;
			for (int j=i+1;j<=n;j++)
				if(fabs(a[j][line])>fabs(a[Max][line])) Max=j;
			for (int j=1;j<=n+1;j++)
				swap(a[Max][j],a[i][j]);
		}
		if(line>n) break;
		for (int j=i+1;j<=n;j++)
		{
			double tmp=a[j][line]/a[i][line];
			for (int k=line;k<=n+1;k++)
				a[j][k]-=a[i][k]*tmp;
		}
	}
}

void fuck()
{
	for (int i=1;i<=n;i++)
	{
		int Max=i;
		for (int j=i+1;j<=n;j++)
			if(fabs(a[j][i])>fabs(a[Max][i])) Max=j;
		if(i!=Max)
			for (int j=1;j<=n+1;j++)
				swap(a[i][j],a[Max][j]);
		if(fabs(a[i][i])<eps)
			continue;
		for (int j=i+1;j<=n+1;j++)
			a[i][j]/=a[i][i];a[i][i]=1;
		for (int j=1;j<=n;j++)
			if(i!=j)
			{
				double tmp=a[j][i];
				for (int k=1;k<=n+1;k++) a[j][k]-=tmp*a[i][k];
			}
	}
}

void work()
{
	Gauss();
	for (int i=1;i<=n;i++,puts(""))
		for (int j=1;j<=n+1;j++)
			printf("%d ",a[i][j]);
	for (int i=1;i<=n;i++)
	{
		int flag=1;
		for (int j=1;j<=n;j++)
			if(fabs(a[i][j])>eps) flag=0;
		if(flag&&fabs(a[i][n+1])>eps) {puts("-1");return;}
	}
	for (int i=1;i<=n;i++)
		if(fabs(a[i][i])<eps) {puts("0");return;}
	memcpy(a,b,sizeof(a));
	fuck();
	for (int i=1;i<=n;i++)
		printf("x%d=%.2lf\n",i,a[i][n+1]);
}

int main()
{
	init();
	work();
	return 0;
}

标签:const,int,luogu,flag,SDOI2006,Max,P2455,line,include
来源: https://www.cnblogs.com/With-penguin/p/12885181.html