Cod sursa(job #1125540)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 26 februarie 2014 18:16:16
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.4 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

const int Nmax = 10002;

vector <int> G[Nmax];
int use[Nmax], st[Nmax], dr[Nmax];

int N, M, E;

int pairup( int nod )
{
    if ( use[nod] )
            return 0;

    use[nod] = 1;

    for ( auto x: G[nod] )
            if ( !dr[x] )
            {
                st[nod] = x;
                dr[x] = nod;
                return 1;
            }

    for ( auto x: G[nod] )
            if ( pairup( dr[x] ) )
            {
                st[nod] = x;
                dr[x] = nod;
                return 1;
            }

    return 0;
}

void Hopcroft_Karp()
{
    for ( int change = 1; change; )
    {
        change = 0;
        memset( use, 0, sizeof ( use ) );

        for ( int i = 1; i <= N; ++i )
                if ( !st[i] )
                        change |= pairup( i );
    }

    int cpl = 0;

    for ( int i = 1; i <= N; ++i )
            cpl += ( st[i] > 0 );

    ofstream g("cuplaj.out");

    g << cpl << "\n";

    for ( int i = 1; i <= N; ++i )
            if ( st[i] )
                    g << i << " " << st[i] << "\n";
}

int main()
{
    ifstream f("cuplaj.in");

    f >> N >> M >> E;

    while ( E-- )
    {
        int a, b;

        f >> a >> b;

        G[a].push_back( b );
    }

    Hopcroft_Karp();

    return 0;
}