为什么会把无数解判成无解啊QAQ

P2455 [SDOI2006] 线性方程组

misinclair @ 2018-06-14 19:57:01

这道题貌似跟普通的高斯消元不一样?

还是我水平太低啊

// luogu-judger-enable-o2
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>

using namespace std;

const int N = 105;
const double eps = 1e-8;
double a[N][N], x[N];
int n;
bool flag = false;

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 i = 1; i <= n; ++i) {
        int p = i;
        for(int j = i + 1; j <= n; ++j)
            if(fabs(a[j][i]) > fabs(a[p][i]))
                p = j;
        if(p != i)
            for(int j = 1; j <= n + 1; ++j)
                swap(a[i][j], a[p][j]);
        if(fabs(a[i][i]) < eps) {
            printf("-1\n");
            return 0;
        }
        for(int j = i + 1; j <= n; ++j) {
            double radio = a[j][i] / a[i][i];
            for(int k = 1; k <= n + 1; ++k)
                a[j][k] -= radio * a[i][k];
        }
    }
    for(int i = n; i; --i) {
        for(int j = i + 1; j <= n; ++j)
            a[i][n + 1] -= x[j] * a[i][j];
        if(fabs(a[i][i]) < eps && fabs(a[i][n + 1]) > eps) {
            printf("-1\n");
            return 0;
        }
        if(fabs(a[i][n + 1]) < eps && fabs(a[i][i]) < eps) 
            flag = true;
        x[i] = a[i][n + 1] / a[i][i];
    }
    if(flag) printf("0\n");
    else {
        for(int i = 1; i <= n; ++i) {
            printf("x%d=", i);
            if(fabs(x[i]) < eps) printf("0\n");
            else printf("%.2lf\n", x[i]);
        }
    }  
    return 0;
}

by DefFrancis @ 2018-06-16 14:32:45

不能把判断无解的情况放在高斯消元的过程中

因为无穷解的时候a[i][i]也是 0

然后得先判无解在判断无穷解

提交10遍得出来的结论


by DefFrancis @ 2018-06-16 19:54:53

@AK_583 QWQ


|