Cod sursa(job #626043)

Utilizator thesilverhand13FII Florea Toma Eduard thesilverhand13 Data 26 octombrie 2011 10:43:38
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
# include <fstream>
# include <vector>
# include <algorithm>

//const char iname[] = "cuplaj.in";
//const char oname[] = "cuplaj.out";

# define MAXN  10005
# define FOR(i, a, b)  for (int i = (int)(a); i <= (int)(b); ++ i)
# define FORI(i, V)    for (vector <int>::iterator i = (V).begin(); i != (V).end(); ++ i)

using namespace std;

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


vector <int> G[ MAXN ];

int l[ MAXN ], r[ MAXN ], u[ MAXN ];


int pairup( const int n )
{
	int i;
    if ( u[ n ] )  
		return 0;
    u[ n ] = 1;
   
	for ( i = 0 ; i < G[ n ].size() ; i++ )
		if ( r[ G[ n ][ i ] ] == 0 )	
		{
			l[ n ] = G[ n ][ i ];
		    r[ G[ n ][ i ] ] = n;
	     	return 1;
		}
    
	for ( i = 0 ; i < G[ n ].size() ; i++ )
		if ( pairup( r[ G[ n ][ i ] ] ) == 1  )	
		{
			l[ n ] = G[ n ][ i ];
		    r[ G[ n ][ i ] ] = n;
		    return 1;
		}
		
		return 0;
}

int main(void)
{
    //freopen(iname, "r", stdin);
    //freopen(oname, "w", stdout);

    int n, m, cnt_edges, i;
    //scanf("%d %d %d", &n, &m, &cnt_edges);
	
	f >> n >> m >> cnt_edges;
	
	for ( i = 1 ; i <= cnt_edges ; i++ )
    {
        int x, y;
		f >> x >> y;
        G[ x ].push_back( y );
    }
    for (int change = 1; change; )
    {
        change = 0;
        memset(u, 0, sizeof(u));
        FOR ( i, 1, n ) 
		if ( !l[ i ] )
            change |= pairup( i );
    }
    int cuplaj = 0;
    //FOR ( i, 1, n )
    for ( i = 1 ; i <= n ; i++ )	
	cuplaj = cuplaj + ( l[ i ] > 0 );
	
    //printf("%d\n", cuplaj );
	g << cuplaj << "\n";
    //FOR ( i, 1, n )
	for ( i = 1 ; i <= n ; i++ )
	if (l[ i ] > 0)
		g << i << " " << l[ i ] <<"\n";

    return 0;
}