Cod sursa(job #401675)

Utilizator ssergiussSergiu-Ioan Ungur ssergiuss Data 23 februarie 2010 00:19:08
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <algorithm>
#include <bitset>
#include <queue>
#include <vector>
using namespace std;

#define DIM 1<<9
#define INF 0x3f3f3f3f

int N, M, S, D, XXX;
int t[ DIM ], cst[ DIM ], flx[ DIM ][ DIM ];
bitset <DIM> f;
queue <int> q;
vector < pair <int, int> > v[ DIM ];

inline int bellman_ford() {

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

    f.reset();
    memset( cst, INF, sizeof( cst ) );
    cst[ S ] = 0;
    for( q.push( S ); !q.empty(); q.pop() ) {

        nod = q.front();
        f[ nod ] = 0;
        for( it = v[ nod ].begin(); it != v[ nod ].end(); ++it )
            if( flx[ nod ][ it->first ] > 0 && cst[ nod ] + it->second < cst[ it->first ] ) {

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

                    q.push( it->first );
                    f[ it->first ] = 1;
                }
            }
    }
    if( cst[ D ] != INF )
        return 1;

    return 0;
}

int main() {

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

    int x, y, nod, cost, fmin, capacitate;

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

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

    while( bellman_ford() ) {

        fmin = INF;
        for( nod = D; t[ nod ]; nod = t[ nod ] )
            fmin = min( fmin, flx[ t[ nod ] ][ nod ] );
        if( fmin ) {

            for( nod = D; t[ nod ]; nod = t[ nod ] ) {

                flx[ t[ nod ] ][ nod ] -= fmin;
                flx[ nod ][ t[ nod ] ] += fmin;
            }
            XXX += fmin * cst[ D ];
        }
    }

    printf( "%d", XXX );

    return 0;
}