Cod sursa(job #1788008)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 25 octombrie 2016 14:32:35
Problema Tunelul groazei Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.93 kb
#include <fstream>
#include <vector>
#include <iomanip>

using namespace std;

ifstream fin ("tunel.in"); ofstream fout ("tunel.out");

typedef vector< int > graf;

const int nmax = 260;
const double eps = 1e-7;
int n, m;
double e[nmax + 1];
double a[nmax + 1][nmax + 1];

inline void update (int x, int y, int c) {
    ++ a[ x ][ x ];
    -- a[ x ][ y ];
    a[ x ][n + 1] += 1.0 * c;
}

void interschimba (int x, int y) {
    for (int i = 1; i <= n + 1; ++ i) {
        swap(a[ x ][ i ], a[ y ][ i ]);
    }
}

void simplifica (int x, int y) {
    double k = a[ x ][ y ];
    for (int i = y; i <= n + 1; ++ i) {
        a[ x ][ i ] /= k;
    }

    for (int i = x + 1; i <= n - 1; ++ i) {
        k = a[ i ][ y ];
        for (int j = 1; j <= n + 1; ++ j) {
            a[ i ][ j ] -= a[ x ][ j ] * k;
        }
    }
}

void gauss() {
    int j = 1;
    for (int i = 1; i <= n - 1; ++ i) {
        int x;

        while (j <= n - 1) {
            x = i;
            while (x <= n - 1 && (-eps < a[ x ][ j ] && a[ x ][ j ] < eps)) {
                ++ x;
            }

            if (x <= n - 1) {
                break;
            }
            ++ j;
        }

        if (j <= n - 1) {
            interschimba(i, x);
            simplifica(i, j);
            ++ j;
        }
    }

    e[ n ] = 0;
    for (int i = n - 1; i > 0; -- i) {
        for (int j = 1; j <= n - 1; ++ j) {
            if (a[ i ][ j ] <= -eps || a[ i ][ j ] >= eps) {
                e[ j ] = a[ i ][n + 1];

                for (int k = j + 1; k <= n; ++ k) {
                    e[ j ] -= e[ k ] * a[ i ][ k ];
                }
                break;
            }
        }
    }
}

int main() {
    fin >> n >> m;
    for (int i = 1; i <= m; ++ i) {
        int x, y, c;
        fin >> x >> y >> c;
        update(x, y, c);
        update(y, x, c);
    }

    gauss();

    fout << setprecision( 3 ) << fixed;
    fout << e[ 1 ] << "\n";

    fin.close();
    fout.close();
    return 0;
}