Cod sursa(job #912826)

Utilizator TeodoraTanaseTeodora Tanase TeodoraTanase Data 12 martie 2013 20:08:50
Problema Algoritmul lui Gauss Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <cstdio>
#include <algorithm>

#define NMAX 301

using namespace std;

int n;
int m;
double a[NMAX][NMAX + 1];

void read()
{
    freopen("gauss.in", "r", stdin);

    scanf("%d %d\n", &n, &m);
    for(int i = 0; i < n; ++ i)
        for(int j = 0; j <= m; ++ j)
            scanf("%lf ", &a[i][j]);
}

int coefPoz(int i)
{
    for(int j = 0; j < m; ++ j)
        if(a[i][j] != 0)
            return j;

    return -1;
}

void swapRow(int r1, int r2)
{
    for(int j = 0; j < m; ++ j)
        swap(a[r1][j], a[r2][j]);
}

void modify(int r1, int r2, double val)
{
    for(int j = 0; j <= m; ++ j)
    {
        double aux = a[r1][j] * val;
        a[r2][j] += aux;
    }
}

void triangle()
{
    for(int i = 0; i < n - 1; ++ i)
    {
        int p = coefPoz(i);

        for(int k = i + 1; k < n; ++ k)
            if(coefPoz(k) < p)
            {
                swapRow(i, k);
                break;
            }

        for(int k = i + 1; k < n; ++ k)
        {
            int q = coefPoz(k);

            if(q == p)
            {
                double val = -a[k][q] / a[i][p];

                modify(i, k, val);
            }
        }
    }
}

void solve()
{
    for(int i = n - 1; i >= 0; -- i)
    {
        for(int j = i + 1; j < m; ++ j)
            a[i][m] -= a[i][j] * a[j][m];

        a[i][m] /= a[i][i];
    }
}

void write()
{
    freopen("gauss.out", "w", stdout);

    for(int i = 0; i < n; ++ i)
        printf("%lf ", a[i][m]);

    printf("\n");
}

int main()
{
    read();
    triangle();
    solve();
    write();

    return 0;
}