Cod sursa(job #984214)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 13 august 2013 20:24:07
Problema Flux maxim Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 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];
bool viz[Nmax];
int C[Nmax][Nmax];
int F[Nmax][Nmax];

queue <int> Q;

int N, M;

void read()
{
    ifstream 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 );
    }

    f.close();
}

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

    Q.push( sourse );
    viz[sourse] = true;

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

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

            viz[G[nod][v]] = true;
            tata[G[nod][v]] = nod;
            Q.push( 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 ); flow += fmin )
    {
        fmin = INF;

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

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

    return flow;
}

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

    g << Edmonds_Karp(1, N);

}

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

    return 0;
}