Cod sursa(job #606981)

Utilizator stay_awake77Cangea Catalina stay_awake77 Data 10 august 2011 15:57:45
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.95 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

#define NMAX 1005
#define pb push_back
#define MIN(a,b) (a<b) ? a : b

using namespace std;

ifstream in("maxflow.in");
ofstream out("maxflow.out");

int C[NMAX][NMAX], F[NMAX][NMAX], T[NMAX], N, M, x, y, Nod, capacitate, MaxFlow, FlowCt;
vector< int > G[NMAX];
vector< int >::iterator Vecin;
bool USED[NMAX];

inline bool BF()
{
    memset( T, 0, sizeof(T) );

    memset( USED, false, sizeof(USED) );
    USED[1] = true;

    queue< int > Q;
    Q.push( 1 );

    while( !Q.empty() )
    {
        int NOD = Q.front();
        Q.pop();

        for( Vecin = G[NOD].begin(); Vecin != G[NOD].end(); Vecin++ )
            if( !USED[*Vecin] && F[NOD][*Vecin] < C[NOD][*Vecin] )
            {
                USED[*Vecin] = true;
                Q.push( *Vecin );
                T[*Vecin] = NOD;
            }
    }

    return USED[N];
}

int main()
{
    memset( C, 0, sizeof(C) );
    memset( F, 0, sizeof(F) );

    in >> N >> M;
    while( M-- )
    {
        in >> x >> y >> capacitate;
        C[x][y] = capacitate;
        G[x].pb( y );
        G[y].pb( x );
    }

    MaxFlow = 0;
    for( ; BF(); )
        for( int i = 1; i < N; i++ )
            if( T[i] && F[i][N] < C[i][N] )
            {
                FlowCt = C[i][N] - F[i][N];
                for( Nod = i; Nod != 1; Nod = T[Nod] )
                    FlowCt = MIN( FlowCt, C[ T[Nod] ][ Nod ] - F[ T[Nod] ][ Nod ] );

                if( FlowCt )
                {
                    F[i][N] += FlowCt;
                    F[N][i] -= FlowCt;

                    for( Nod = i; Nod != 1; Nod = T[Nod] )
                    {
                        F[ T[Nod] ][Nod] += FlowCt;
                        F[Nod][ T[Nod] ] -= FlowCt;
                    }

                    MaxFlow += FlowCt;
                }
            }

    out << MaxFlow << '\n';

    return 0;
}