Cod sursa(job #622648)

Utilizator valentina506Moraru Valentina valentina506 Data 18 octombrie 2011 12:07:04
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.93 kb
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>

#define NMAX 1005
#define INF (1<<30)

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

using namespace std;

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

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

inline bool BF()
{
    queue< int > Q;
    Q.push( 1 );

    memset( USED, false, sizeof(USED) );
    USED[1] = true;
	
    while( !Q.empty() )
    {
        int NOD = Q.front();
        Q.pop();
        if( NOD != N )
            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 >> cost;
        C[x][y] = cost;
        G[x].pb( y );
        G[y].pb( x );
    }
    MaxFlow = 0;
  //  for( ; BF(); )
	while(BF())
        for( Vecin = G[N].begin(); Vecin != G[N].end(); Vecin++ )
            if( USED[*Vecin] && F[*Vecin][N] < C[*Vecin][N] )
            {
                T[N] = *Vecin;
                FlowCt = INF;
                for( Nod = N; Nod != 1; Nod = T[Nod] )
                    FlowCt = MIN( FlowCt, C[ T[Nod] ][ Nod ] - F[ T[Nod] ][ Nod ] );
                if( FlowCt )
                    for( Nod = N; Nod != 1; Nod = T[Nod] )
                    {
                        F[ T[Nod] ][ Nod ] += FlowCt;
                        F[ Nod ][ T[Nod] ] -= FlowCt;
                    }
                MaxFlow += FlowCt;
            }
			
    out << MaxFlow << '\n';

    return 0;
}