Cod sursa(job #988555)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 23 august 2013 11:10:29
Problema Cuplaj maxim in graf bipartit Scor 28
Compilator cpp Status done
Runda Arhiva educationala Marime 2.53 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <cstring>
#include <unordered_map>

using namespace std;

#define Nmax 20050

vector <int> G[Nmax];
unordered_map < int, int > F[Nmax], C[Nmax];

bool viz[Nmax];
int coada[Nmax];
int tata[Nmax];

int N, M, E;
int S, D;

void read()
{
    ifstream f("cuplaj.in");

    f >> N >> M >> E;

    S = 0, D = N + M + 1;

    for ( int i = 1, a, b; i <= E; ++i )
    {
        f >> a >> b;

        a = a;
        b = b + N;

        C[S][a] = 1;
        G[S].push_back( a );
        G[a].push_back( S );

        C[a][b] = 1;
        G[a].push_back( b );
        G[b].push_back( a );


        C[b][D] = 1;

        G[b].push_back( D );
        G[D].push_back( b );
    }

    f.close();
}

inline bool BFS( int sourse, int destination )
{
    memset( viz, 0, sizeof( viz ) );

    int st, dr;

    coada[st = dr = 1] = sourse;
    viz[sourse] = 1;

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

        for ( unsigned i = 0; i < G[nod].size(); ++i )
        {
            int vertex = G[nod][i];

            if ( !viz[vertex] && C[nod][vertex] > F[nod][vertex] )
            {
                tata[vertex] = nod;
                viz[vertex] = 1;

                coada[ ++dr ] = vertex;

                if ( vertex == destination )
                        return true;
            }
        }
    }

    return false;
}

int Edmonds_Karp( int sourse, int destination )
{
    int flow = 0, fmin, nod;

    while( BFS( sourse, destination ) )
    {
        for ( unsigned i = 0; i < G[destination].size(); ++i )
        {
            int son = G[destination][i];

            if ( !viz[son] || F[son][destination] >= C[son][destination] )
                    continue;

            fmin = 1e10;
            tata[destination] = son;

            for ( nod = destination; nod != sourse; nod = tata[nod] )
                    fmin = min( fmin, C[ tata[nod] ][nod] - F[ tata[nod] ][nod] );

            if ( !fmin )
                    continue;

            for ( nod = destination; nod != sourse; nod = tata[nod] )
            {
                F[ tata[nod] ][nod] += fmin;
                F[nod][ tata[nod] ] -= fmin;
            }

            flow += fmin;
        }
    }

    return flow;
}

void print()
{
    ofstream g("cuplaj.out");

    g << Edmonds_Karp( S, D ) << "\n";

    g.close();
}

int main()
{
    read();
    print();

    return 0;
}