Cod sursa(job #985087)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 16 august 2013 14:16:20
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.03 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

#define Nmax 10002

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

int N, M, E, nr;

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

    f >> N >> M >> E;

    string FD( ( istreambuf_iterator<char>(f) ), istreambuf_iterator<char>() );

    unsigned l = FD.length();
    int v[4] = { 0 };
    int cont = 0;
    int nr = 0;

    for ( unsigned i = 1; i < l; ++i )
            if ( isdigit( FD[i] ) )
                    nr = nr * 10 + ( FD[i] - 48 );
            else
            {
                v[ ++cont ] = nr;

                if ( cont == 2 )
                {
                    G[v[1]].push_back( v[2] );
                    cont = 0;
                }

                nr = 0;
            }

    f.close();
}

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

    use[nod] = 1;

    for ( unsigned i = 0; i < G[nod].size(); ++i )
            if ( !dr[ G[nod][i] ] )
            {
                st[nod] = G[nod][i];
                dr[ G[nod][i] ] = nod;

                return 1;
            }

    for ( unsigned i = 0; i < G[nod].size(); ++i )
            if ( pairup( dr[ G[nod][i] ] ) )
            {
                st[nod] = G[nod][i];
                dr[ G[nod][i] ] = nod;

                return 1;
            }

    return 0;
}

void cuplaj()
{
    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 );
    }

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

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

    g << nr << '\n';

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

    g.close();
}

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

    return 0;
}