Cod sursa(job #1677516)

Utilizator CrystyAngelDinu Cristian CrystyAngel Data 6 aprilie 2016 17:13:22
Problema Algoritmul lui Gauss Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.08 kb
#include <cstdio>
#include <cmath>
#include <iostream>
using namespace std;
double d[310][310],e[310][310],s,x[310];
int n,m,ok;
bool schimba(int a,int b)
{
    int i,k,j;
    for(i=a+1; i<n; ++i)
        if(d[i][b])
            break;
    k=i;
    if(k==n)
        return 0;
    for(j=b; j<m; ++j)
        swap(d[i][j],d[a][j]);
    return 1;
}
int main()
{
    freopen("gauss.in","r",stdin);
    freopen("gauss.out","w",stdout);
    scanf("%d%d",&n,&m);
    int i,j,k;
    if(n<m)
        printf("Imposibil\n");
    else
    {
        ok=1;
        for(i=0; i<n; ++i)
            for(j=0; j<=m; ++j)
                {
                    scanf("%lf",&e[i][j]);
                    d[i][j]=e[i][j];
                }
        for(i=0; i<m; ++i)
            {
                if(!d[i][i])
                    {
                        ok=schimba(i,j);
                        if(!ok)
                        {
                            printf("Imposibil");
                            break;
                        }
                    }
                for(k=i+1; k<n; ++k)
                    {
                        for(j=i+1; j<m; ++j)
                            d[k][j]=d[k][j]-(double)d[i][j]*(double)d[k][i]/d[i][i];
                    }
                for(j=m; j>=i; --j)
                    d[i][j]/=d[i][i];
            }
        if(ok)
        for(i=m-1; i>=0; --i)
        {
            x[i]=d[i][m];
            for(j=m-1; j>i; --j)
                x[i]-=x[j]*d[i][j];
        }
        if(ok)
            {
         /*       for(i=0; i<n; ++i)
                {
                    s=0;
                    for(j=0; j<m; ++j)
                        s+=x[j]*e[i][j];
                    if(abs(e[i][j]-s)>0.001)
                    {
                        ok=0;
                        break;
                    }
                }*/
                if(ok)
                for(i=0; i<m; ++i)
                    printf("%.10lf ",x[i]);
                else
                    printf("Imposibil");
            }
    }
}