# 高斯消元一

"好aoaoaoaoaoaoa"的高斯消元模板题

## 做法

### 第三点注意

（形如 x × 0 = y , x × -1 = y | x>0 && y>0,肯定无解）

# 代码

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <queue>
#include <cmath>
#define rg register int
#define ll long long
#define RG register
#define il inline
using namespace std;

il int gi()
{
rg x=0,o=0;RG char ch=getchar();
while(ch!='-'&&(ch<'0'||'9'<ch)) ch=getchar();
if(ch=='-') o=1,ch=getchar();
while('0'<=ch&&ch<='9') x=(x<<1)+(x<<3)+ch-'0',ch=getchar();
return o?-x:x;
}

int n,m;
#define db double
db x[1001],fc[1001][501];

il int gauss()
{
RG bool flg=0;
for(rg now,k=1; k<=n; ++k)
{
now=k;
for(rg i=k+1; i<=m; ++i)
if(fabs(fc[i][k])>fabs(fc[now][k]))
now=i;
if(now==k && fabs(fc[k][k])<1e-7)
{
flg=1;
continue;
}
if(now!=k) swap(fc[now],fc[k]);
for(rg i=k+1; i<=n+1; ++i) fc[k][i]/=fc[k][k];fc[k][k]=1;
for(rg i=k+1; i<=m; ++i)
{
for(rg j=k+1; j<=n+1; ++j)
fc[i][j]-=fc[i][k]*fc[k][j];
fc[i][k]=0;
}
}
for(rg j,i=1; i<=m; ++i)
{
for(j=1; j<=n; ++j)
if(fabs(fc[i][j])>1e-6)
break;
if(j==n+1 && fabs(fc[i][n+1])>1e-6) return 0; // 如果 方程系数小于0并且结果大于 0 则无解
}
for(rg i=n; i>=1; --i)
{
for(rg j=i+1; j<=n; ++j) fc[i][n+1]-=fc[i][j]*fc[j][n+1];
if(fc[i][n+1] && !fc[i][i] ) return 0;
}
if(flg) return -1;
return 1;
}
int main()
{
n=gi(),m=gi();
for(rg i=1; i<=m; ++i)
for(rg j=1; j<=n+1; ++j)
scanf("%lf",&fc[i][j]);
rg ans=gauss();
if(ans==-1) puts("Many solutions");
else if(ans==0) puts("No solutions");
else for(rg i=1; i<=n; ++i) printf("%d\n",(int)(fc[i][n+1]+0.5));
return 0;
}

posted @ 2018-02-10 10:40  TPLY  阅读(...)  评论(...编辑  收藏