Cod sursa(job #2017778)

Utilizator Tiberiu02Tiberiu Musat Tiberiu02 Data 2 septembrie 2017 15:12:19
Problema Flux maxim Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
# include <iostream>
# include <fstream>
# include <algorithm>
# include <vector>
# include <deque>
# include <cstring>

using namespace std;

const int MAX_N = 1000;
int flow[1 + MAX_N][1 + MAX_N];
int p[1 + MAX_N];

vector<int> bords[1 + MAX_N];

int bfs( int s, int d ) {
    memset( p, 0, sizeof( p ) );

    deque< pair<int, int> > q;
    q.push_back( make_pair( 1e9, s ) );

    while ( q.size() ) {
        pair<int, int> t = q.back();
        q.pop_back();

        int f = t.first;
        int u = t.second;

        if ( u == d )
            return f;
        else {
            for ( int v : bords[u] )
                if ( flow[u][v] > 0 && !p[v] ) {
                    p[v] = u;
                    q.push_back( make_pair( min( f, flow[u][v] ), v ) );
                }
        }
    }

    return false;
}

int randInt( int n ) {
    return rand() % n;
}

int main() {
    srand( time( NULL ) );

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

    int n, m;
    fin >> n >> m;

    for ( int i = 0; i < m; i ++ ) {
        int x, y, c;
        fin >> x >> y >> c;
        flow[x][y] = c;
        if ( !flow[y][x] ) {
            bords[x].push_back( y );
            bords[y].push_back( x );
        }
    }

    for ( int i = 1; i <= n; i ++ )
        random_shuffle( bords[i].begin(), bords[i].end(), randInt );

    int total_f = 0, f = bfs( 1, n );
    while ( f > 0 ) {
        total_f += f;

        for ( int u = n; u != 1; u = p[u] ) {
            flow[p[u]][u] -= f;
            flow[u][p[u]] += f;
        }
        f = bfs( 1, n );
    }

    fout << total_f;

    return 0;
}