Cod sursa(job #1163235)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 1 aprilie 2014 11:32:10
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

const int Nmax = 10000;

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

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( ostream &g )
{
    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 cuplaj = 0;

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

    g << cuplaj << "\n";

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

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

    f >> N >> M >> E;

    for ( int i = 1, x ,y; i <= E; ++i )
    {
        f >> x >> y;

        G[x].push_back( y );
    }

    Hopcroft_Karp( g );

    return 0;
}