Cod sursa(job #1715439)

Utilizator laurageorgescuLaura Georgescu laurageorgescu Data 10 iunie 2016 18:06:12
Problema Flux maxim de cost minim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include<fstream>
#include<vector>
#include<queue>
#include<cstring>

using namespace std;

ifstream fin( "fmcm.in" ); ofstream fout( "fmcm.out" );

typedef vector< int > graf;

const int nmax = 350;
const int inf = (1 << 30);
int n, S, D;
int t[ nmax + 1 ];
bool v[ nmax + 1 ];
int d[ nmax + 1 ];
int c[ nmax + 1 ][ nmax + 1 ];
int cost[ nmax + 1 ][ nmax + 1 ];
graf g[ nmax + 1 ];

queue< int > q;

bool bellman_ford() {
    for( int i = 1; i <= n; ++ i ) {
        d[ i ] = inf;
        v[ i ] = 0;
    }
    d[ S ] = 0;
    q.push( S );
    v[ S ] = 1;

    while ( !q.empty() ) {
        int x = q.front();
        q.pop();
        v[ x ] = 0;

        for( auto it : g[ x ] ) {
            if ( c[ x ][ it ] > 0 && d[ x ] + cost[ x ][ it ] < d[ it ] ) {
                t[ it ] = x;
                d[ it ] = d[ x ] + cost[ x ][ it ];

                if ( v[ it ] == 0 ) {
                    q.push( it );
                    v[ it ] = 1;
                }
            }
        }
    }
    return d[ D ] != inf;
}
int main() {
    int m;
    fin >> n >> m >> S >> D;

    for( int i = 1; i <= m; ++ i ) {
        int x, y;
        fin >> x >> y;
        fin >> c[ x ][ y ] >> cost[ x ][ y ];
        cost[ y ][ x ] = -cost[ x ][ y ];
        g[ x ].push_back( y );
        g[ y ].push_back( x );
    }

    long long ans = 0;
    while ( bellman_ford() ) {
        int fluxmin = inf;

        for( int x = D; x != S; x = t[ x ] ) {
            if ( c[ t[ x ] ][ x ] < fluxmin ) {
                fluxmin = c[ t[ x ] ][ x ];
            }
        }
        for( int x = D; x != S; x = t[ x ] ) {
            ans += 1LL * cost[ t[ x ] ][ x ] * fluxmin;
            c[ t[ x ] ][ x ] -= fluxmin;
            c[ x ][ t[ x ] ] += fluxmin;
        }
    }

    fout << ans << "\n";

    fin.close();
    fout.close();
    return 0;
}