Cod sursa(job #1607809)

Utilizator DysKodeTurturica Razvan DysKode Data 21 februarie 2016 16:57:24
Problema Flux maxim Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.76 kb
#include <fstream>
#include <vector>
#include <cstring>
#include <queue>

using namespace std;

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

int Cap[1010][1010],n,m,i,x,y,c,Tree[1010],D,S,flow,mini;
bool ok;
vector <int> Graf[ 1010 ];
queue <int> Q;

void GetBfsTree( int start )
{
    memset( Tree , 0 , sizeof( Tree ) );
    Q.push( start );
    while( Q.size() )
    {
        for( auto it : Graf[ Q.front() ] )
        {
            if( Cap[ Q.front() ][ it ] > 0 && it != S && it != D && Tree[ it ] == 0 )
            {
                Tree[ it ] = Q.front();
                Q.push( it );
            }
        }
        Q.pop();
    }
}

int GetMin( int nod )
{
    int ans = Cap[ nod ][ D ];
    while( Tree[ nod ] != 0 )
    {
        ans = min( ans , Cap[ Tree[ nod ] ][ nod ] );
        nod = Tree[ nod ];
    }
    return ans;
}

void Sat( int nod, int val )
{
    Cap[ nod ][ D ] -= val;
    while( Tree[ nod ] != 0 )
    {
        Cap[ Tree[ nod ] ][ nod ] -= val;
        Cap[ nod ][ Tree[ nod ] ] += val;
        nod = Tree[ nod ];
    }
}

int main()
{
    fin>>n>>m;
    S = 1;
    D = n;
    for( i = 1; i <= m ; i++ )
    {
        fin>>x>>y>>c;
        Graf[ x ].push_back( y );
        Cap[ x ][ y ] = c;
    }

    flow = Cap[ S ][ D ];
    Cap[ S ][ D ] = 0;

    while( true )
    {
        GetBfsTree( S );
        ok = false;
        for( i = 2 ; i < n ; i++ )
        {
            if(  Tree[ i ] != 0 && Cap[ i ][ D ] > 0 )
            {
                ok = true;
                mini = GetMin( i );
                flow += mini;
                Sat( i , mini );
            }
        }
        if( !ok )
            break;
    }
    fout<<flow;

    return 0;
}