新人求助高斯消元

P2455 [SDOI2006] 线性方程组

zrz_orz @ 2019-09-28 20:12:49

4,8数据点 WA

#include <bits/stdc++.h>

// Defination {{{
#define PI std::pair<int, int>
#define mk std::make_pair
#define reg register
#define ll long long
#define rep(i, a, b) for(reg int i = a; i <= b; ++i)
#define per(i, a, b) for(reg int i = a; i >= b; --i)
#define pb push_back
#define debug(...) fprintf(stderr, __VA_ARGS__)
// }}}

template<typename T> T max(T a, T b) { return a > b ? a : b; }
template<typename T> T min(T a, T b) { return a < b ? a : b; }

template<typename T> void read(T &x) {
    x = 0; reg char ch = getchar(); reg int f = 1;
    for (; !isdigit(ch); ch = getchar()) if (ch == '-') f = -1;
    for (; isdigit(ch); ch = getchar()) x = (x << 1) + (x << 3) + (ch ^ 48);
    x *= f;
}

#define N 55

int n;
long double a[N][N], ans[N];

inline int gauss_jordan() {
    rep (i, 1, n) {
        int Max = i;
        rep (j, i + 1, n) if (fabs(a[j][i]) > fabs(a[Max][i])) Max = j; 
        if (Max != i) std::swap(a[Max], a[i]);
        if (fabs(a[i][i] - 0.0) < 1e-10) return -1;
        rep (j, 1, n) {
            if (j == i) continue;
            long double div = a[j][i] / a[i][i];
            rep (k, i + 1, n + 1) a[j][k] -= a[i][k] * div;
        }
    }
    rep (i, 1, n) if (fabs(a[i][i] - 0.0) < 1e-10 && fabs(a[i][n + 1] - 0.0) < 1e-10) return 0;
    return 1;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("2455.in", "r", stdin);
    freopen("2455.out", "w", stdout);
#endif
    read(n);
    rep (i, 1, n) rep (j, 1, n + 1) scanf ("%Lf", &a[i][j]);
    int check = gauss_jordan();
    if (check != 0 && check != -1) {
        rep (i, 1, n) ans[i] = a[i][n + 1] / a[i][i];
        rep (i, 1, n) {
            if (fabs(ans[i] - 0.0) < 1e-10) printf("x%d=0\n", i);
            else printf("x%d=%.2Lf\n", i, a[i][n + 1] / a[i][i]);
        }
    }
    else printf("%d\n", check);
    return 0; 
}

/*
 _____  ____    _____
|__  / |  _ \  |__  /
  / /  | |_) |   / / 
 / /_  |  _ <   / /_ 
/____| |_| \_\ /____|

 ________________________________________ 
< 2455.cpp is created by zrz who is weak >
 ---------------------------------------- 
        \   ^__^
         \  (^^)\_______
            (__)\       )\/\
             U ||----w |
                ||     ||

*/

by justin_cao @ 2019-09-28 20:15:46

%%%


by No268435 @ 2019-09-28 20:20:52

%%%


by Kewth @ 2019-09-28 20:25:11

%%%


by Enquir @ 2019-09-28 21:40:50

%%% 大括号不换行的邪教


by 祥瑞御免 @ 2019-09-29 09:08:03

%%%


by Jean @ 2019-09-29 14:10:12

%%%


|