Cod sursa(job #611470)

Utilizator stay_awake77Cangea Catalina stay_awake77 Data 1 septembrie 2011 18:00:58
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <fstream>
#include <vector>
#include <cstring>

#define NMAX 20001
#define pb push_back

using namespace std;

ifstream in("cuplaj.in");
ofstream out("cuplaj.out");

vector< int > G[NMAX];
int N1, N2, M, x, y, i, CuplajMax = 0, St[NMAX], Dr[NMAX], Lanturi;
bool USED[NMAX];

inline bool Cupleaza( int NOD )
{
    if( USED[NOD] ) return false;
    USED[NOD] = 1;

    for( vector< int >::iterator Vecin = G[NOD].begin(); Vecin != G[NOD].end(); Vecin++ )
        if( !Dr[*Vecin] )
        {
            St[NOD] = *Vecin;
            Dr[*Vecin] = NOD;

            return true;
        }

    for( vector< int >::iterator Vecin = G[NOD].begin(); Vecin != G[NOD].end(); Vecin++ )
        if( Cupleaza( Dr[*Vecin] ) )
        {
            St[NOD] = *Vecin;
            Dr[*Vecin] = NOD;

            return true;
        }

    return false;
}

int main()
{
    in >> N1 >> N2 >> M;
    for( ; M--; )
    {
        in >> x >> y;
        G[x].pb( y );
    }

    memset( St, 0, sizeof(St) );
    memset( Dr, 0, sizeof(Dr) );

    for( Lanturi = 1; Lanturi; )
    {
        Lanturi = 0;
        memset( USED, false, sizeof(USED) );

        for( i = 1; i <= N1; i++ )
            if( !St[i] )
                Lanturi += (int)Cupleaza( i );
    }
    for( i = 1; i <= N1; i++ )
        CuplajMax += (int)( St[i] > 0 );

    out << CuplajMax << '\n';
    for( i = 1; i <= N1; i++ )
        if( St[i] ) out << i << ' ' << St[i] << '\n';

    return 0;
}