Cod sursa(job #412355)

Utilizator ssergiussSergiu-Ioan Ungur ssergiuss Data 5 martie 2010 15:20:47
Problema Flux maxim Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.55 kb
#include <algorithm>
#include <bitset>
#include <queue>
#include <vector>

using namespace std;

#define INF 0x3f3f3f3f
#define MAX_N 1<<10
#define MAX_S 1<<13

char s[ MAX_S ];
int N, M;
int cnt_s, flux, t[ MAX_N ], cap[ MAX_N ][ MAX_N ], flx[ MAX_N ][ MAX_N ];
bitset <MAX_N> f;
queue <int> q;
vector <int> v[ MAX_N ];

int bellman_ford() {

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

    f.reset();
    memset( t, 0, sizeof( t ) );

    q.push( 1 );
    f[ 1 ] = true;

    while( !q.empty() ) {

        if( q.front() == N ) {

            q.pop();
            continue;
        }

        nod = q.front();
        q.pop();

        for( it = v[ nod ].begin(); it != v[ nod ].end(); ++it )
            if( cap[ nod ][ *it ] - flx[ nod ][ *it ] > 0 ) {

                t[ *it ] = nod;

                if( f[ *it ] == false ) {

                    f[ *it ] = true;
                    q.push( *it );
                }
            }
    }

    return f[ N ];
}

void read( int &val ) {

    while( !isdigit( s[ cnt_s ] ) )
        if( ++cnt_s == MAX_S ) {

            fread( s, 1, MAX_S, stdin );
            cnt_s = 0;
        }

    val = 0;
    while( isdigit( s[ cnt_s ] ) ) {

        val = val * 10 + s[ cnt_s ] - '0';
        if( ++cnt_s == MAX_S ) {

            fread( s, 1, MAX_S, stdin );
            cnt_s = 0;
        }
    }
}

int main() {

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

    int x, y, cp, nod, f_min;
    vector <int> :: iterator it;

    cnt_s = MAX_S - 1;

    read( N );
    read( M );

    while( M-- ) {

        read( x );
        read( y );
        read( cp );

        v[ x ].push_back( y );
        v[ y ].push_back( x );
        cap[ x ][ y ] = cp;
    }

    while( bellman_ford() )
        for( it = v[ N ].begin(); it != v[ N ].end(); ++it )
            if( f[ *it ] == true && cap[ *it ][ N ] - flx[ *it ][ N ] > 0 ) {

                f_min = INF;
                t[ N ] = *it;

                for( nod = N; nod != 1; nod = t[ nod ] )
                    f_min = min( f_min, cap[ t[ nod ] ][ nod ] - flx[ t[ nod ] ][ nod ] );

                if( 0 < f_min && f_min < INF ) {

                    for( nod = N; nod != 1; nod = t[ nod ] ) {

                        flx[ t[ nod ] ][ nod ] += f_min;
                        flx[ nod ][ t[ nod ] ] -= f_min;
                    }
                    flux += f_min;
                }
            }

    printf( "%d", flux );

    return 0;
}