Cod sursa(job #403265)

Utilizator ssergiussSergiu-Ioan Ungur ssergiuss Data 24 februarie 2010 19:35:29
Problema Flux maxim de cost minim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.2 kb
#include <algorithm>
#include <bitset>
#include <queue>
#include <vector>
using namespace std;

#define DIM 355
#define INF 0x3f3f3f3f

short int N, M, S, D;
short int t[ DIM ], cap[ DIM ][ DIM ], flx[ DIM ][ DIM ];
int XXX;
int val[ DIM ];
bitset <DIM> f;
vector < pair <short int, short int> > v[ DIM ];

struct cmp {

    bool operator()( const int &a, const int &b ) {

        return val[ a ] > val[ b ];
    }
};
priority_queue < int, vector <int>, cmp > heap;

inline int bellman_ford() {

    short int nod;
    int fmin;
    vector < pair <short int, short int> > :: iterator it;

    f.reset();
    memset( val, INF, sizeof( val ) );

    val[ S ] = 0;
    heap.push( S );
    while( !heap.empty() ) {

        nod = heap.top();
        heap.pop();
        f[ nod ] = 0;
        for( it = v[ nod ].begin(); it != v[ nod ].end(); ++it )
            if( cap[ nod ][ it->first ] > flx[ nod ][ it->first ] && val[ nod ] + it->second < val[ it->first ] ) {

                val[ it->first ] = val[ nod ] + it->second;
                t[ it->first ] = nod;
                if( !f[ it->first ] ) {

                    heap.push( it->first );
                    f[ it->first ] = 1;
                }
            }
    }
    if( val[ D ] != INF ) {

        fmin = INF;
        for( nod = D; nod != S; nod = t[ nod ] )
            fmin = min( fmin, cap[ t[ nod ] ][ nod ] - flx[ t[ nod ] ][ nod ] );
        for( nod = D; nod != S; nod = t[ nod ] ) {

            flx[ t[ nod ] ][ nod ] += fmin;
            flx[ nod ][ t[ nod ] ] -= fmin;
        }

        return fmin * val[ D ];
    }

    return 0;
    }

int main() {

    freopen( "fmcm.in", "r", stdin );
    freopen( "fmcm.out", "w", stdout );

    short int x, y, cost, capacitate;
    int ok;

    scanf( "%hd %hd %hd %hd", &N, &M, &S, &D );
    while( M-- ) {

        scanf( "%hd %hd %hd %hd", &x, &y, &capacitate, &cost );
        v[ x ].push_back( make_pair( y, cost ) );
        v[ y ].push_back( make_pair( x, -cost ) );
        cap[ x ][ y ] = capacitate;
    }

    do {

        ok = bellman_ford();
        XXX += ok;
    }
    while( ok );

    printf( "%d", XXX );

    return 0;
}