Cod sursa(job #1163218)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 1 aprilie 2014 11:25:27
Problema Flux maxim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

const int Nmax = 100;
const int inf = 1e9;

vector <int> G[Nmax + 1];
int C[Nmax + 1][Nmax + 1];
int F[Nmax + 1][Nmax + 1];
int tata[Nmax + 1], vis[Nmax + 1], coada[Nmax + 1];

int N, M;

int BFS( int S, int D )
{
    for ( int i = 1; i <= N; ++i )
            vis[i] = 0;

    int st, dr;
    coada[st = dr = 1] = S;
    tata[S] = 0;
    vis[S] = 1;

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

        for ( auto x: G[nod] )
        {
            if ( !vis[x] && C[nod][x] > F[nod][x] )
            {
                vis[x] = 1;
                tata[x] = nod;
                coada[ ++dr ] = x;

                if ( x == D )
                        return 1;
            }
        }
    }

    return 0;
}

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

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

            tata[D] = x;
            fmin = inf;

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

            if ( !fmin ) continue;

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

            flow += fmin;
        }
    }

    return flow;
}

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

    f >> N >> M;

    for ( int i = 1, x, y, z; i <= M; ++i )
    {
        f >> x >> y >> z;

        G[x].push_back( y );
        G[y].push_back( x );

        C[x][y] = z;
    }

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

    return 0;
}