niiick @ 2018-11-06 11:52:40
板子A过洛谷P3389 【模板】高斯消元法,复制过来加入无穷多解的判断就WA
最后两组数据是要输出无解但是我一直得出无穷多解
手动造数据测了好像也没什么问题QAQ
#include<iostream>
#include<cmath>
#include<algorithm>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
typedef double dd;
int read()
{
int f=1,x=0;
char ss=getchar();
while(ss<'0'||ss>'9'){if(ss=='-')f=-1;ss=getchar();}
while(ss>='0'&&ss<='9'){x=x*10+ss-'0';ss=getchar();}
return f*x;
}
const int maxn=410;
const dd eps=1e-8;
int n;
dd a[maxn][maxn];
dd ans[maxn];
int gauss()
{
for(int i=1;i<=n;++i)
{
int r=i;
for(int j=i+1;j<=n;++j)
if(fabs(a[j][i])>fabs(a[r][i])) r=j;
if(fabs(a[r][i])<eps) return 0;
if(r!=i) swap(a[i],a[r]);
dd f=a[i][i];
for(int j=i;j<=n+1;j++) a[i][j]/=f;
for(int j=i+1;j<=n;j++)
{
f=a[j][i];
for(int k=i;k<=n+1;k++)
a[j][k]-=a[i][k]*f;
}
}
int judge=0;
for(int i=1;i<=n;++i)
{
int cnt=0;
for(int j=1;j<=n;++j)
if(fabs(a[i][j])<eps) cnt++;
if(cnt==n&&fabs(a[i][n+1])>eps) return -1;
if(cnt==n) judge=1;
}
if(judge) return 0;
for(int i=n;i>=1;i--)
{
ans[i]=a[i][n+1];
for(int j=i+1;j<=n;j++)
ans[i]-=(a[i][j]*ans[j]);
}
return 1;
}
int main()
{
n=read();
for(int i=1;i<=n;++i)
for(int j=1;j<=n+1;++j)
scanf("%lf",&a[i][j]);
int tt=gauss();
if(tt!=1) printf("%d",tt);
else{
for(int i=1;i<=n;++i)
if(fabs(ans[i])<eps) printf("x%d=0\n",i);
else printf("x%d=%.2lf\n",i,ans[i]);
}
return 0;
}
by Caro23333 @ 2018-11-06 11:55:52
刚学OI的都是怪物.jpg
by 天上一颗蛋 @ 2018-11-06 11:58:58
%%%
by Viva_lemon @ 2018-11-06 11:59:44
%%%
by meowko @ 2018-11-06 12:00:44
%%%
by King_of_gamers @ 2018-11-06 12:06:07
你怕是个dalao+妹纸
by 浮尘ij @ 2018-11-06 14:13:30
%%%
刚学OI就学高斯消元,我刚学OI那会儿都不知道在干嘛
by Monster_Qi @ 2018-11-06 14:24:23
您好,为什么您强调您不是妹子呢?
by niiick @ 2018-11-06 16:37:22
上面好像贴错了一份代码,不过貌似都没人回答蒟蒻的问题啊=_=
#include<iostream>
#include<cmath>
#include<algorithm>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
typedef double dd;
int read()
{
int f=1,x=0;
char ss=getchar();
while(ss<'0'||ss>'9'){if(ss=='-')f=-1;ss=getchar();}
while(ss>='0'&&ss<='9'){x=x*10+ss-'0';ss=getchar();}
return f*x;
}
const int maxn=410;
const dd eps=1e-8;
int n;
dd a[maxn][maxn];
dd ans[maxn];
int gauss()
{
for(int i=1;i<=n;++i)
{
int r=i;
for(int j=i+1;j<=n;++j)
if(fabs(a[j][i])>fabs(a[r][i])) r=j;
if(fabs(a[r][i])<eps) return -1;
if(r!=i) swap(a[i],a[r]);
dd f=a[i][i];
for(int j=i;j<=n+1;j++) a[i][j]/=f;
for(int j=i+1;j<=n;j++)
{
f=a[j][i];
for(int k=i;k<=n+1;k++)
a[j][k]-=a[i][k]*f;
}
}
int judge=0;
for(int i=1;i<=n;++i)
{
int cnt=0;
for(int j=1;j<=n;++j)
if(fabs(a[i][j])<eps) cnt++;
if(cnt==n&&fabs(a[i][n+1])>eps) return -1;
if(cnt==n) judge=1;
}
if(judge) return 0;
for(int i=n;i>=1;i--)
{
ans[i]=a[i][n+1];
for(int j=i+1;j<=n;j++)
ans[i]-=(a[i][j]*ans[j]);
}
return 1;
}
int main()
{
n=read();
for(int i=1;i<=n;++i)
for(int j=1;j<=n+1;++j)
scanf("%lf",&a[i][j]);
int tt=gauss();
if(tt!=1) printf("%d",tt);
else{
for(int i=1;i<=n;++i)
if(fabs(ans[i])<eps) printf("x%d=0\n",i);
else printf("x%d=%.2lf\n",i,ans[i]);
}
return 0;
}