高斯消元 WA 9 求助

P2455 [SDOI2006] 线性方程组

UperFicial @ 2022-09-19 08:40:42

#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iostream>
#include<set>
#include<vector>
#include<queue>
#include<stack>
#include<cstring>
#include<cstdlib>
#include<ctime>
#define rep(i,a,b) for(register int i=a;i<=b;++i)
#define rev(i,a,b) for(register int i=a;i>=b;--i)
#define gra(i,u) for(register int i=head[u];i;i=edge[i].nxt)
#define Clear(a) memset(a,0,sizeof(a))
#define yes puts("YES")
#define no puts("NO")
using namespace std;
typedef long long ll;
const int INF(1e9+10);
const ll LLINF(1e18+10);
inline int read()
{
    int s=0,w=1;
    char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
    while(ch>='0'&&ch<='9')s=s*10+(ch-'0'),ch=getchar();
    return s*w;
}
template<typename T>
inline T Min(T x,T y){return x<y?x:y;}
template<typename T>
inline T Max(T x,T y){return x>y?x:y;}
template<typename T>
inline void Swap(T&x,T&y){T t=x;x=y;y=t;return;}
template<typename T>
inline T Abs(T x){return x<0?-x:x;}

const int MAXN(60);
const double eps(1e-9);

int n;
double a[MAXN][MAXN],ans[MAXN];
bool f1=false,f2=false;

inline bool check()
{
    rep(i,1,n)
    {
        bool flag=false;
        rep(j,1,n) if(fabs(a[i][j])>eps){flag=true;break;}
        if(!flag)
        {
            if(fabs(a[i][n+1])<eps) f2=true;
            else f1=true;
        }
    }
    if(f1) puts("-1");
    else if(f2) puts("0");
    else return true;
    return false;
}

inline void guess()
{
    rep(i,1,n)
    {
        int p=i;
        rep(j,i+1,n) if(fabs(a[p][i])<fabs(a[j][i])) p=j;
        rep(j,1,n+1) Swap(a[i][j],a[p][j]);
        if(fabs(a[i][i])<eps)
        {
            f2=true;
            continue;
        }
        double div=a[i][i];
        rep(j,i,n+1) a[i][j]/=div;
        rep(j,i+1,n)
        {
            div=a[j][i];
            rep(k,i,n+1) a[j][k]-=a[i][k]*div;
        }
    }
    ans[n]=a[n][n+1]/a[n][n];
    rev(i,n-1,1)
    {
        ans[i]=a[i][n+1];
        rep(j,i+1,n) ans[i]=ans[i]-ans[j]*a[i][j];
        ans[i]/=a[i][i];
    }
    if(check()) rep(i,1,n) printf("x%d=%.2lf\n",i,ans[i]);
    return;
}

int main()
{
//  freopen("read.txt","r",stdin);
    n=read();
    rep(i,1,n) rep(j,1,n+1) scanf("%lf",&a[i][j]);
    guess();
    return 0;
}
/*
Date : 2022/9/19
Author : UperFicial
Start coding at : 8:05
finish debugging at :
*/

|