Cod sursa(job #456535)

Utilizator alexandru92alexandru alexandru92 Data 15 mai 2010 21:18:32
Problema Flux maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.31 kb
/*
 * File:   main.cpp
 * Author: virtualdemon
 *
 * Created on May 15, 2010, 7:54 PM
 */
#include <queue>
#include <cstdlib>
#include <fstream>
#include <algorithm>
#define Nmax 400
#define oo 0x3f3f3f3f

/*
 *
 */
using namespace std;
typedef pair< int, int > pr;
int N, source, sink;
int d[Nmax], f[Nmax];
int C[Nmax][Nmax], D[Nmax][Nmax];
vector< int > v;
vector< int > G[Nmax];
vector< int >::const_iterator it, iend;
struct cmp
{
    inline bool operator() ( const int& x, const int& y ) const
    {
        return d[x] > d[y];
    }
};
inline bool find_path( void )
{
    int x;
    vector< bool > inH( N+1 );
    priority_queue< int, vector< int >, cmp > pQ;
    fill( d+1, d+N+1, oo );
    f[source]=0;
    d[source]=0;
    for( pQ.push(source); !pQ.empty(); )
    {
        x=pQ.top(); pQ.pop();
        inH[x]=false;
        for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
        {
            if( source == *it )
                continue;
            if( C[x][*it] > 0 && d[x]+D[x][*it] < d[*it] )
            {
                f[*it]=x;
                d[*it]=d[x]+D[x][*it];
                if( false == inH[*it] )
                {
                    pQ.push(*it);
                    inH[*it]=true;
                }
            }
        }
    }
    return oo != d[sink];
}
int main( void )
{
    int M, x, y, c;
    ifstream in( "fmcm.in" );
    for( in>>N>>M>>source>>sink; M; --M )
    {
        in>>x>>y;
        in>>C[x][y]>>D[x][y];
        D[y][x]=-D[x][y];
        G[x].push_back(y);
        G[y].push_back(x);
        if( sink == x )
            v.push_back(y);
        else if( sink == y )
                v.push_back(x);
    }
    for( x=0; find_path(); )
    {
        for( it=v.begin(), iend=v.end(); it < iend; ++it )
        {
            M=*it;
            if( d[sink] == d[M]+D[M][sink] && C[M][sink] > 0 )
            {
                c=C[M][sink];
                for( y=M; f[y]; y=f[y] )
                    if( c > C[f[y]][y] )
                        c=C[f[y]][y];
                C[M][sink]-=c;
                C[sink][M]+=c;
                for( y=M; f[y]; y=f[y] )
                {
                    C[f[y]][y]-=c;
                    C[y][f[y]]+=c;
                }
                x+=c*d[sink];
            }
        }
    }
    ofstream out( "fmcm.out" );
    out<<x<<'\n';
    return EXIT_SUCCESS;
}