Cod sursa(job #1204478)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 3 iulie 2014 00:10:43
Problema Flux maxim Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.8 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <algorithm>

using namespace std;

const int Nmax = 1e3 + 2;

vector <int> G[Nmax];

int C[Nmax][Nmax];
int F[Nmax][Nmax];

int father[Nmax];
int coada[Nmax];

int N, M;

void add_edge( int i, int j, int c )
{
    G[i].push_back( j );
    C[i][j] = c;
}

bool BFS( int S, int D )
{
    int st, dr;

    coada[st = dr = 1] = S;
    father[S] = S;
    fill( father + 1, father + N + 1, 0 );

    while ( st <= dr )
    {
        int nod = coada[ st++ ];

        for ( auto vecin: G[nod] )
        {
            if ( father[vecin] == 0 && C[nod][vecin] > F[nod][vecin] )
            {
                father[vecin] = nod;
                coada[ ++dr ] = vecin;

                if ( vecin == D )
                    return true;
            }
        }
    }

    return false;
}

int Edmonds_Karp( int S, int D )
{
    int flow = 0, fmin;

    while ( BFS( S, D ) )
    {
        for ( auto x: G[D] )
        {
            if ( !father[x] || F[x][D] >= C[x][D] ) continue;

            father[D] = x;
            fmin = 1e9;

            for ( int nod = D; nod != S; nod = father[nod] )
                    fmin = min( fmin, C[ father[nod] ][nod] - F[ father[nod] ][nod] );

            if ( !fmin ) continue;

            for ( int nod = D; nod != S; nod = father[nod] )
            {
                F[ father[nod] ][nod] += fmin;
                F[nod][ father[nod] ] -= fmin;
            }

            flow += fmin;
        }
    }

    return flow;
}

int main()
{
    ifstream in("maxflow.in");
    ofstream out("maxflow.out");

    in >> N >> M;

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

        add_edge( a, b, c );
        add_edge( b, a, 0 );
    }

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

    return 0;
}