蒟蒻求助 WA # 1 read -, expected 0.

P2455 [SDOI2006] 线性方程组

Trump_ @ 2023-02-16 11:09:02

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>

using namespace std;

int n,nowline;
double a[11451][11451];

inline int find_pivot( int column ) {
    int maxn = column;
    for (int i = column + 1; i <= n; ++i) {
        if ( a[i][column] > a[maxn][column] ) {
            maxn = i;
        }
    }
    return maxn;
}

inline void swap_line( int now , int need ) {
    //now表示现在这一行 need表示需要的行
    for (int i = 1; i <= n + 1; ++i) {
        swap( a[now][i] , a[need][i] );
    } 
    return; 
}

int main()
{
    scanf("%d",&n);
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n + 1; ++j) {
            scanf("%lf",&a[i][j]);
        }
    }
    for (int q = 1,i = 1; q <= n; ++q) {
        //i表示第及行 q表示第几列 
        int pivot = find_pivot( i );
        if ( a[pivot][q] == 0 ) continue;
        //如果此列全为0则先跳过,可以先不用管 
        swap_line( i , pivot ); 
        for (int j = 1; j <= n; ++j) {
            if ( j != i ) {
                double temp = a[j][q] / a[i][q];
                for (int k = q;k <= n + 1; ++k) {
                    a[j][k] -= ( a[i][k] * temp );
                }
            }
        }//正常高斯约旦消元 
        i ++;
        nowline = i;
    }
    if ( nowline <= n ) {
        for (int i = nowline; i <= n; ++i) {
            if ( a[i][n + 1] != 0 ) {
                //其中有k*x = a;
                //若 k = 0 a != 0 则无解 输出-1 
                //若 k = 0 a = 0 则无穷解 输出0 
                //注意在同时是无解和无穷解的情况下方程组属于无解 
                printf ("-1\n");
                return 0;
            }
        }
        printf ("0\n");
        return 0;
    }
    for (int i = 1; i <= n; ++i) {      
        a[i][n + 1] /= a[i][i];//除上系数
        printf ( "x%d=" , i );
        printf ( "%.2lf\n" , a[i][n + 1] );
    }
    return 0;
}

by iterator_traits @ 2023-02-16 11:10:26

可能是遇到-0了,特判一下


by Trump_ @ 2023-02-16 11:22:55

谢谢巨佬,等我先看看


by Trump_ @ 2023-02-16 11:25:32

不是这个的锅,像

3
0 0 1 1
0 1 0 1
0 1 0 1

就不对


by Trump_ @ 2023-02-16 11:59:07

因为find_pivot函数的column出错了,应该用column = q才对,谢谢奆佬,此贴结


|