求助高斯消元

P2455 [SDOI2006] 线性方程组

火羽白日生 @ 2021-02-05 21:29:40

rt

WA #4 #8

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <stdlib.h>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
#include <stack>

typedef long long ll;
typedef unsigned long long ull;
using namespace std;

inline int read(){
    char ch=getchar(); int x=0,w=1;
    while(ch<'0'||ch>'9') {if(ch=='-') w=-1; ch=getchar();}
    while(ch>='0'&&ch<='9') {x=(x<<3)+(x<<1)+(ch^48); ch=getchar();}
    return x*w;
}

const int maxn=55;
const double eps=1e-12;
int n,flag;
double a[maxn][maxn],ans[maxn];

int gauss(){
    int cnt=0;
    for(int i=1;i<=n;i++){
        int maxx=i;
        for(int j=i+1;j<=n;j++)
            if(fabs(a[maxx][i])<fabs(a[j][i]))
                maxx=j;
        if(fabs(a[maxx][i])<eps) continue;
        if(i!=maxx) swap(a[i],a[maxx]);
        double div=a[i][i];
        for(int j=i;j<=n+1;j++)
            a[i][j]/=div;
        for(int j=i+1;j<=n;j++){
            div=a[j][i];
            for(int k=i;k<=n+1;k++)
                a[j][k]-=a[i][k]*div;
        }
        cnt++;
    }
    if(cnt<n){
        int start=cnt;
        for(int i=start;i<=n;i++)
            if(fabs(a[i][n])>eps)
                return 2;
        return 1;
    }
    ans[n]=a[n][n+1];
    for(int i=n-1;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 0;
}

int main(int argc, const char * argv[]) {
    n=read();
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n+1;j++)
            a[i][j]=read();
    flag=gauss();
    if(flag==2) puts("-1");
    else if(flag==1) puts("0");
    else{
        for(int i=1;i<=n;i++)
            printf("x%d=%.2lf\n",i,ans[i]);
    }
    return 0;
}

by Rui_R @ 2021-02-05 21:35:49

@LiBoyi 给你组数据

2
0 2 3
0 0 0

答案应该是0。


by cmll02 @ 2021-02-06 22:01:10

萌新刚学搞死小圆,求助


|