Cod sursa(job #448889)

Utilizator alexandru92alexandru alexandru92 Data 4 mai 2010 22:14:33
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
/* 
 * File:   main.cpp
 * Author: virtualdemon
 *
 * Created on May 4, 2010, 9:22 PM
 */
#include <queue>
#include <cstdlib>
#include <fstream>
#define Nmax 20011
#define oo 0x3f3f3f3f

/*
 * 
 */
using namespace std;
int N;
int d[Nmax], P[Nmax];
vector< int > G[Nmax];
vector< int >::const_iterator it, iend;
inline bool bfs( void )
{
    int x;
    queue< int > Q;
    for( x=1; x <= N; ++x )
        if( !P[x] )
            d[x]=0, Q.push(x);
        else d[x]=oo;
    d[0]=oo;
    while( !Q.empty() )
    {
        x=Q.front(); Q.pop();
        if( !x )
            continue;
        for( it=G[x].begin(), iend=G[x].end(); it < iend; ++it )
            if( oo == d[P[*it]] )
            {
                d[P[*it]]=d[x]+1;
                Q.push(P[*it]);
            }
    }
    return d[0] != oo;
}
inline bool PairUp( int x )
{
    if( !x )
        return true;
    vector< int >::const_iterator it=G[x].begin(), iend=G[x].end();
    for( ; it < iend; ++it )
        if( d[P[*it]] == d[x]+1 && PairUp(P[*it]) )
        {
            P[x]=*it;
            P[*it]=x;
            return true;
        }
    d[x]=oo;
    return false;
}
int main(int argc, char** argv)
{
    int M, E, x, y, nrc=0;
    ifstream in( "cuplaj.in" );
    for( in>>N>>M>>E; E; --E )
    {
        in>>x>>y;
        G[x].push_back(y);
    }
    while( bfs() )
    {
        for( x=1; x <= N; ++x )
            if( !P[x] && PairUp(x) )
                ++nrc;
    }
    ofstream out( "cuplaj.out" );
    out<<nrc<<'\n';
    for( x=1; nrc && x <= N; ++x )
        if( P[x] )
            out<<x<<' '<<P[x]<<'\n', --nrc;
    return (EXIT_SUCCESS);
}