Cod sursa(job #1159416)

Utilizator Dddarius95Darius-Florentin Neatu Dddarius95 Data 29 martie 2014 16:16:34
Problema Flux maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.3 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <cstring>
#include <algorithm>

using namespace std;
ifstream f("fmcm.in");
ofstream g("fmcm.out");
const int Nmax = 355;
const int oo = 0x3f3f3f3f;

typedef pair<int,int> node;

vector <int> G[Nmax];
priority_queue < node, vector <node>, greater<node> > heap;

int ante[Nmax], dist[Nmax], old_dist[Nmax], real_dist[Nmax];
int C[Nmax][Nmax], Cost[Nmax][Nmax];

int N, M, S, D;
int solution;

void read()
{


    f >> N >> M >> S >> D;

    for ( int i = 1; i <= M; ++i )
    {
        int a, b, c, z;

        f >> a >> b >> c >> z;

        G[a].push_back( b );
        G[b].push_back( a );

        C[a][b] = c;

        Cost[a][b] = z;
        Cost[b][a] = -z;
    }

    f.close();
}

inline bool Dijkstra()
{
    memset( dist, oo, sizeof( dist ) );

    dist[S] = real_dist[S] = 0;
    heap.push( node( 0, S ) );

    while( !heap.empty() )
    {
        int nod = heap.top().second;
        int val = heap.top().first;

        heap.pop();

        if( dist[nod] != val )
                continue;

        for( unsigned i = 0; i < G[nod].size(); i++ )
        {
            int son = G[nod][i];

            if( C[nod][son] )
            {
                int cost = dist[nod] + Cost[nod][son] + old_dist[nod] - old_dist[son];

                if( cost < dist[son] )
                {
                    ante[son] = nod;
                    dist[son] = cost;
                    real_dist[son] = real_dist[nod] + Cost[nod][son];

                    heap.push( node( dist[son], son ) );
                }
            }
        }
    }

    memcpy( old_dist, real_dist, sizeof( old_dist ) );

    return ( dist[D] != oo );
}

void Edmonds_Karp()
{
    while( Dijkstra() )
    {
        int fmin = oo;

        for ( int nod = D; nod != S; nod = ante[nod] )
                fmin = min( fmin, C[ ante[nod] ][nod] );

        for ( int nod = D; nod != S; nod = ante[nod] )
        {
            C[ ante[nod] ][nod] -= fmin;
            C[nod][ ante[nod] ] += fmin;
        }

        solution += fmin * real_dist[D];
    }
}

void print()
{


    g << solution << "\n";

    g.close();
}

int main()
{
    read();
    Edmonds_Karp();
    print();

    return 0;
}