Cod sursa(job #2190728)

Utilizator PopoviciRobertPopovici Robert PopoviciRobert Data 31 martie 2018 17:09:13
Problema Algoritmul lui Gauss Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 305;
const double eps = 1e-7;

double mat[MAXN + 1][MAXN + 1];
double sol[MAXN + 1];

int main() {
    FILE *fi, *fout;
    int i, j, n, m;
    fi = fopen("gauss.in" ,"r");
    fout = fopen("gauss.out" ,"w");
    fscanf(fi,"%d %d " ,&n,&m);
    for(i = 1; i <= n; i++) {
        for(j = 1; j <= m + 1; j++)
            fscanf(fi,"%f " ,&mat[i][j]);
    }
    int l = 1, c = 1;
    while(l <= n && c <= m) {
        i = l;
        while(i <= n && abs(mat[i][c]) < eps)
            i++;
        if(i == n + 1)
            c++;
        else {
            for(j = c; j <= m + 1; j++)
                swap(mat[i][j], mat[l][j]);
            for(j = c + 1; j <= m + 1; j++) {
                mat[l][j] /= mat[l][c];
            }
            mat[l][c] = 1.0;
            for(i = l + 1; i <= n; i++) {
                for(j = c + 1; j <= m + 1; j++) {
                    mat[i][j] -= mat[i][c] * mat[l][j];
                }
                mat[i][c] = 0.0;
            }
            l++;
            c++;
        }
    }
    for(i = n; i >= 1; i--) {
        j = 1;
        while(j <= m && abs(mat[i][j]) < eps)
            j++;
        if(j == m + 1) {
            if(abs(mat[i][j]) > eps) {
                fprintf(fout,"Imposibil");
                return 0;
            }
        }
        else {
            for(int p = j + 1; p <= c; p++) {
                mat[i][m + 1] -= sol[p] * mat[i][p];
            }
            sol[j] = mat[i][m + 1];
        }
    }
    for(i = 1; i <= m; i++) {
        fprintf(fout,"%.8lf " ,sol[i]);
    }
    fclose(fi);
    fclose(fout);
    return 0;
}