Cod sursa(job #1781879)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 17 octombrie 2016 16:03:05
Problema Tunelul groazei Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.65 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax = 260;
const double eps = 1e-8;

int n, m;
vector < pair < int, int > > g[nmax];

double a[nmax][nmax];

void read_input()
{
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= m; ++i)
    {
        int x, y, c;
        scanf("%d %d %d", &x, &y, &c);

        g[x].push_back({y, c});
        g[y].push_back({x, c});
    }
}

void prepare_gauss()
{
    for (int i = 1; i < n; ++i)
    {
        a[i][i] = 1.0;
        for (auto it : g[i])
            a[i][it.first] -= 1.0 / (int)g[i].size(),
            a[i][n+1] += 1.0 * it.second / (int)g[i].size();
    }

    a[n][n] = 1.0; a[n][n+1] = 0.0;
}

int compare(double a, double b)
{
    if (a + eps < b) return -1;
    if (b + eps < a) return 1;
    return 0;
}

double run_gauss(int n, int m)
{
    for (int i = 1; i <= n; ++i)
    {
        int p = 0;
        for (int j = 1; j <= m + 1 && !p; ++j)
            if (compare(a[i][j], 0) != 0)
                p = j;

        if (p == 0)
            continue;

        for (int k = 1; k <= n; ++k)
        {
            if (k == i || !compare(a[k][p], 0))
                continue;

            double coef = a[k][p] / a[i][p];
            for (int j = 1; j <= m + 1; ++j)
                a[k][j] -= a[i][j] * coef;
        }
    }

    return a[1][m+1] / a[1][1];
}

void print_answer(double ans)
{
    printf("%.5f\n", ans);
    exit(0);
}

int main()
{
    freopen("tunel.in","r",stdin);
    freopen("tunel.out","w",stdout);

    read_input();
    prepare_gauss();
    double ans = run_gauss(n, n);
    print_answer(ans);

    return 0;
}