Cod sursa(job #442502)

Utilizator alexandru92alexandru alexandru92 Data 14 aprilie 2010 18:12:14
Problema Flux maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
/* 
 * File:   main.cpp
 * Author: VirtualDemon
 *
 * Created on April 14, 2010, 3:51 PM
 */
#include <queue>
#include <cstdlib>
#include <fstream>
#define Nmax 400
#define oo 0x3f3f3f3f

/*
 *
 */
using namespace std;
typedef pair< int, int > pr;
int N, s, sk;
int C[Nmax][Nmax];
int d[Nmax], f[Nmax];
vector< pr > G[Nmax];
vector< pr >::const_iterator it, iend;
class cmp
{
public:
    inline bool operator() ( const int& x, const int& y ) const
    {
        return d[x] > d[y];
    }
};
priority_queue< int, vector< int >, cmp > PQ;
inline int find_path( void )
{
    int x, c;
    vector< bool > inH( N );
    for( x=0; x < N; d[x]=oo, ++x );
    d[s]=0;
    f[s]=f[sk]=-1;
    for( PQ.push(s); !PQ.empty();  )
    {
        x=PQ.top(); PQ.pop();
        inH[x]=false;
        for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
            if( C[x][it->first] > 0 && d[it->first] > d[x]+it->second )
            {
                f[it->first]=x;
                d[it->first]=d[x]+it->second;
                if( !inH[it->first] )
                {
                    PQ.push(it->first);
                    inH[it->first]=true;
                }
            }
    }
    if( -1 == f[sk] )
        return 0;
    for( x=sk, c=oo; -1 != f[x]; x=f[x] )
        c=min( c, C[f[x]][x] );
    for( x=sk; -1 != f[x]; x=f[x] )
    {
        C[x][f[x]]+=c;
        C[f[x]][x]-=c;
    }
    return d[sk]*c;
}
inline int MaxFlowMinCost( void )
{
    int s, p;
    for( s=0, p=find_path(); p; s+=p, p=find_path() );
    return s;
}
int main( void )
{
    int M, x, y, c;
    ifstream in( "fmcm.in" );
    in>>N>>M>>s>>sk;
    --s, --sk;
    for( ; M; --M )
    {
        in>>x>>y;
        --x, --y;
        in>>C[x][y]>>c;
        G[x].push_back( pr( y, c ) );
        G[y].push_back( pr( x, -c ) );
    }
    ofstream out( "fmcm.out" );
    out<<MaxFlowMinCost()<<'\n';
    return EXIT_SUCCESS;
}