Cod sursa(job #959888)

Utilizator matei_cChristescu Matei matei_c Data 9 iunie 2013 12:11:44
Problema Flux maxim Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.08 kb
#include<fstream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
using namespace std ;

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

#define maxn 1001
#define inf ( 1 << 32 ) - 1

int N, M ;
vector<int> graf[maxn] ;
int cap[maxn][maxn] ;

int ocupat[maxn][maxn] ;
int tata[maxn] ;
bool sel[maxn] ;

queue<int> coada ;

bool bfs()
{
    memset( sel, false, sizeof(sel) ) ;
    coada.push(1) ;
    sel[1] = true ;

    while( coada.empty() == false )
    {
        int nod = coada.front() ;
        coada.pop() ;

        if( nod == N )
            continue ;

        for(size_t i = 0; i < graf[nod].size(); ++i )
        {
            int vecin = graf[nod][i] ;

            if( cap[nod][vecin] == ocupat[nod][vecin] || sel[vecin] == true )
                continue ;

            sel[vecin] = 1 ;
            coada.push(vecin) ;
            tata[vecin] = nod ;
        }
    }

    return sel[N] ;
}

int main()
{
    fin >> N >> M ;

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

        cap[x][y] += z ;
        graf[x].push_back(y) ;
        graf[y].push_back(x) ;
    }

    int flux = 0 ;

    while( bfs() == true )
    {
        for(size_t i = 0; i < graf[N].size(); ++i )
        {
            int nod = graf[N][i] ;
            if( ocupat[nod][N] == cap[nod][N] || sel[nod] == false )
                continue ;

            tata[N] = nod ;

            int fmin = inf ;

            nod = N ;
            while( nod != 1 )
            {
                fmin = min( fmin, cap[ tata[nod] ][nod] - ocupat[ tata[nod] ][nod] ) ;
                nod = tata[nod] ;
            }

            if( fmin == 0 )
                continue ;

            nod = N ;
            while( nod != 1 )
            {
                ocupat[ tata[nod] ][nod] += fmin ;
                ocupat[nod][ tata[nod] ] -= fmin ;
                nod = tata[nod] ;
            }

            flux += fmin ;
        }
    }

    fout << flux ;

    return 0 ;
}