Cod sursa(job #801229)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 23 octombrie 2012 19:13:24
Problema Tunelul groazei Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.97 kb
#include <cstdio>
#include <vector>
#include <cmath>
#include <algorithm>
#include <cassert>

#define v first
#define c second

using namespace std;

const int MaxN = 260;
const double Eps = 1e-8;

vector< pair<int, int> > G[MaxN];

vector<double> A[MaxN];
int N, M;
double X[MaxN];
bool Sol;

void BuildSystem() {
    for (int i = 1; i <= N; ++i)
        A[i].resize(M+2, 0.0);
    for (int x = 1; x < N; ++x) {
        double p = G[x].size();
        A[x][x] = 1;
        for (vector< pair<int, int> >::iterator y = G[x].begin(); y != G[x].end(); ++y)
            A[x][y->v] += -1.0/p, A[x][M+1] += y->c/p;
    }
}

void ComputeSolution() {
    Sol = true;
    for (int i = 1, j; i <= N; ++i) {
        for (j = 1; j <= M+1; ++j)
            if (abs(A[i][j]) > Eps)
                break;
        if (j == M+1) {
            Sol = false; return;
        }
        X[j] = A[i][M+1]/A[i][j];
    }
}

inline void Reduce(vector<double> &L1, vector<double> &L2, double C) {
    for (int i = 1; i <= M+1; ++i)
        L1[i] += C*L2[i];
}

void Gauss() {
    int i = 1, j = 1;
    while (i <= N && j <= M) {
        int k;
        for (k = i; k <= N && abs(A[k][j]) < Eps; ++k);
        if (k == N+1) {
            ++j; continue;
        }
        swap(A[i], A[k]);
        for (int k = 1; k <= N; ++k)
            if (i != k)
                Reduce(A[k], A[i], -A[k][j]/A[i][j]);
        ++i, ++j;
    }
}

void Solve() {
    BuildSystem();
    Gauss();
    ComputeSolution();
}

void Read() {
    assert(freopen("tunel.in", "r", stdin));
    int E; assert(scanf("%d %d", &N, &E) == 2); M = N;
    for (; E > 0; --E) {
        int x, y, c; assert(scanf("%d %d %d", &x, &y, &c) == 3);
        G[x].push_back(make_pair(y, c)), G[y].push_back(make_pair(x, c));
    }
}

void Print() {
    assert(freopen("tunel.out", "w", stdout));
    printf("%.8lf\n", X[1]);
}

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