萌新求助高斯消元 WA on #3#7#10

P2455 [SDOI2006] 线性方程组

shyr @ 2022-03-18 13:39:06

rt,非常感谢

#include<bits/stdc++.h>
using namespace std;
int n;
double a[55][55], ans[55];
const double eps = 1e-8;
int check(double x){
    if(fabs(x) <= eps) return 0;
    if(x > 0) return 1;
    return -1;
}
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;
        }
        for(int j = 1; j <= n + 1; ++j) swap(a[i][j], a[p][j]);
        for(int j = i + 1; j <= n; ++j){
            double ratio = a[j][i] / a[i][i];
            for(int k = 1; k <= n + 1; ++k){
                a[j][k] -= a[i][k] * ratio;
            }
        }
    }
    for(int i = n; i >= 1; --i){
        for(int j = n; j > i; --j){
            if(check(a[i][j]) == 0) break;
            a[i][n + 1] -= a[i][j] * ans[j];
        }
        if(check(a[i][i]) == 0 && check(a[i][n + 1]) != 0){
            return printf("-1"), 0;
        }
        if(check(a[i][i]) == 0 && check(a[i][n + 1]) == 0){
            return printf("0"), 0;
        }
        ans[i] = a[i][n + 1] / a[i][i];
        if(check(ans[i]) == 0) ans[i] = 0;
    }
    for(int i = 1; i <= n; ++i) printf("x%d=%.2lf\n", i, ans[i]);
}

by ThreeBlueOneBrown @ 2022-03-18 13:43:46

hack:

2
0 2 3
0 0 0

0

参考这个

xxs 不应该说话,溜了溜了


by shyr @ 2022-03-18 13:45:43

@gaoweisong123 ?后面那句话不是很理解


by ThreeBlueOneBrown @ 2022-03-18 13:46:43

xxs 不应该说话,溜了溜了 出自我的梗

大前提:xxs 不应该说话

小前提:gws 比 xxs 还 xxs

结论:gws 应该 溜了溜了


|