Gauss高斯消元——模板

就是线性代数的初等行变化:

  • 倍加。
  • 倍乘。
  • 交换行。
#include 
#define mp make_pair
#define pb push_back

using namespace std;

typedef long long ll;
typedef pair pii;
typedef unsigned long long ull;

const double pi = acos(-1.0);
const double eps = 1e-7;
const int inf = 0x3f3f3f3f;

inline ll read() {
    ll f = 1, x = 0;
    char c = getchar();
    while(c < '0' || c > '9') {
        if(c == '-')    f = -1;
        c = getchar();
    }
    while(c >= '0' && c <= '9') {
        x = (x << 1) + (x << 3) + (c ^ 48);
        c = getchar();
    }
    return f * x;
}

const int N = 110;

double maze[N][N], ans[N];
int n;

bool Gauss() {
    for(int i = 1; i <= n; i++) {
        int max_r = i;
        for(int j = i + 1; j <= n; j++)
            if(fabs(maze[max_r][i]) < fabs(maze[j][i]))
                max_r = j;
        if(fabs(maze[max_r][i]) < eps)  return true;
        if(max_r != i)  swap(maze[i], maze[max_r]);
        double temp = maze[i][i];
        for(int j = i; j <= n + 1; j++)
            maze[i][j] /= temp;
        for(int j = i + 1; j <= n; j++) {
            temp = maze[j][i];
            for(int k = i; k <= n + 1; k++)
                maze[j][k] -= temp * maze[i][k];
        }
    }
    for(int i = n; i >= 1; i--) {
        ans[i] = maze[i][n + 1];
        // ans[(int)maze[i][0]] = maze[i][n + 1];
        for(int j = 1; j < i; j++) {
            double temp = maze[j][i];
            maze[j][i] -= temp;
            maze[j][n + 1] -= maze[i][n + 1] * temp;
        }
    }
    return false;
}

int main () {
    // freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
    // ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    n = read();
    for(int i = 1; i <= n; i++) {
        maze[i][0] = i;
        for(int j = 1; j <= n + 1; j++)
            maze[i][j] = read();
    }
    if(Gauss()) {
        puts("No Solution");
        return 0;
    }
    for(int i = 1; i <= n; i++)
        printf("%.2f\n", ans[i]);
    return 0;
}

你可能感兴趣的:(Gauss高斯消元——模板)