Cod sursa(job #984291)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 13 august 2013 23:50:29
Problema Flux maxim Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.28 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <cstring>

using namespace std;

#define Nmax 1005
#define INF 0x3f3f3f3f

vector <int> G[Nmax];
int tata[Nmax];
int viz[Nmax];
int C[Nmax][Nmax];
int F[Nmax][Nmax];
int coada[Nmax];

queue <int> Q;

int N, M;

void read()
{
    fstream f( "maxflow.in", ios::in );

    f >> N >> M;

    for ( int i = 1, a, b, c; i <= M; ++i )
    {
        f >> a >> b >> c;

        C[a][b] = c;
        G[a].push_back( b );
        G[b].push_back( a );
    }

    f.close();
}

inline bool BFS( int sourse, int destination )
{
    memset( viz, 0, sizeof( viz ) );

    int st, fn;

    coada[st = fn = 1] = 1;

    viz[sourse] = 1;

    for (; st <= fn; )
    {
        int nod = coada[st++];

        for ( unsigned v = 0; v < G[nod].size(); ++v )
        {
            if ( !viz[ G[nod][v] ] && !( F[nod][ G[nod][v] ] >= C[nod][ G[nod][v] ] ) ){

                viz[ G[nod][v] ] = 1;
                tata[ G[nod][v] ] = nod;

                coada[ ++fn ] = G[nod][v];

                if ( G[nod][v] == destination )
                        return true;
            }
        }
    }

    return false;
}

int Edmonds_Karp( int sourse, int destination )
{
    int flow, fmin, nod;

    for ( flow = 0; BFS( sourse, destination ); )
    {
        for ( unsigned i = 0; i < G[destination].size(); ++i )
        {
            if ( !viz[ G[destination][i] ] || ( F[ G[destination][i] ][destination] >= C[ G[destination][i] ][destination] ) )
                    continue;

            fmin = INF;

            tata[destination] = G[destination][i];

            for ( nod = destination; nod != sourse; nod = tata[nod] )
                    fmin = min( fmin, C[ tata[nod] ][nod] - F[ tata[nod] ][nod] );

            if ( fmin == 0 )
                    continue;

            for ( nod = destination; nod != sourse; nod = tata[nod] )
            {
                F[ tata[nod] ][nod] += fmin;
                F[nod][ tata[nod] ] -= fmin;
            }

            flow += fmin;
        }
    }

    return flow;
}

void print()
{
    ofstream g("maxflow.out");

    g << Edmonds_Karp( 1, N ) << "\n";

}

int main()
{
    read();
    print();

    return 0;
}