Cod sursa(job #1162985)

Utilizator romircea2010FMI Trifan Mircea Mihai romircea2010 Data 1 aprilie 2014 08:59:32
Problema Tunelul groazei Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.31 kb
#include <cstdio>
#include <vector>
#include <cmath>

using namespace std;

const int NMax = 260, MMax = 100010;
const double EPS = 1e-9;

struct graph
{
    int node;
    double cost;
    graph () {node = cost = 0;}
    graph (const int node, const double cost)
    {
        this -> node = node;
        this -> cost = cost;
    }
};
vector <graph> G[NMax];

int N, M;
double coef[NMax][NMax], dp[NMax];
int grad[NMax];

void Read()
{
    FILE *f = fopen("tunel.in", "r");
    fscanf(f, "%d %d", &N, &M);
    for (int i = 1; i <= M; ++ i)
    {
        int x, y;
        double cost;
        fscanf(f, "%d %d %lf", &x, &y, &cost);
        G[x].push_back(graph(y, cost));
        G[y].push_back(graph(x, cost));
        ++grad[x], ++grad[y];
    }
    fclose(f);
}

void CreateCoef()
{
    coef[N][N] = 1.0;
    for (int i = N - 1; i > 0; -- i)
    {
        double sum = 0;
        coef[i][i] = grad[i];
        for (vector <graph> :: iterator it = G[i].begin(); it != G[i].end(); ++ it)
        {
            sum += it -> cost;
            coef[i][it -> node] = -1.0;
        }
        coef[i][N + 1] = sum;
    }
}

void DoGauss()
{
    int ec = 1, nec = 1;
    while (ec <= N && nec <= N)
    {
        int i, j;
        if (fabs(coef[ec][nec]) < EPS)
        {
            for (i = ec + 1; ec <= N; ++ i)
                if (fabs(coef[i][nec]) > EPS)
                    break;
            if (i == N + 1)
            {
                ++nec;
                continue;
            }
            else
            {
                for (j = 1; j <= N + 1; ++ j)
                    swap(coef[i][j], coef[ec][j]);
            }
        }
        for (i = 1; i <= N; ++ i)
        {
            if (i == ec)
                continue;
            double raport = coef[i][nec] / coef[ec][nec];
            for (int j = 1; j <= N + 1; ++ j)
                coef[i][j] -= coef[ec][j] * raport;
        }
        ++ec, ++nec;
    }
    dp[N] = 0.0;
    for (int i = N - 1; i > 0; -- i)
        dp[i] = coef[i][N + 1] / coef[i][i];
}

void Solve()
{
    CreateCoef();
    DoGauss();
}

void Write()
{
    FILE *g = fopen("tunel.out", "w");
    fprintf(g, "%.9lf\n", dp[1]);
    fclose(g);
}

int main()
{
    Read();
    Solve();
    Write();
    return 0;
}