高斯消元80pts代码求调(无穷解误判无解)

P2455 [SDOI2006] 线性方程组

Wilderness_ @ 2024-03-26 22:58:50

rt

#include<bits/stdc++.h>
#define db double
using namespace std;
const db eps=1e-7;
db coef[444][444],ans[444]; 
int n,cnt=1;
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;++i)
        for(int j=1;j<=n+1;++j)
            scanf("%lf",&coef[i][j]);
    for(int i=1;i<=n;i++)
    {
        int maxn=i;
        for(int j=i+1;j<=n;++j)if(fabs(coef[maxn][i])<fabs(coef[j][i]))maxn=j;
        if(fabs(coef[maxn][i])<=eps)continue;
        if(i!=maxn)swap(coef[i],coef[maxn]);
        db tmp=coef[i][i];
        for(int j=i;j<=n+1;++j)coef[i][j]/=tmp;
        for(int j=i+1;j<=n;++j)
        {
            tmp=coef[j][i];
            for(int k=i;k<=n+1;++k)coef[j][k]-=coef[i][k]*tmp;
        }
        cnt++;
    }
    if(cnt<=n)
    {
        for(int i=cnt+1;i<=n;i++)
            if(fabs(coef[i][n+1])>=eps)
            {
                puts("-1");return 0;
            }
        puts("0");  
        return 0;
    }
    ans[n]=coef[n][n+1];
    for(int i=n-1;i>=1;i--)
    {
        ans[i]=coef[i][n+1];
        for(int j=i+1;j<=n;j++)ans[i]-=(coef[i][j]*ans[j]);
    }
    for(int i=1;i<=n;i++)printf("x%d=%.2lf\n",i,ans[i]);
}

by Wilderness_ @ 2024-03-26 23:00:34

注:WA #3 #7 hack#1


by 滑不拉稽 @ 2024-03-27 16:13:28

3
0 1 1 2
0 0 3 9
0 0 5 15

来自 Link。


by Wilderness_ @ 2024-03-27 20:08:11

本人已过,此贴结


|