Cod sursa(job #448096)

Utilizator alexandru92alexandru alexandru92 Data 2 mai 2010 18:04:25
Problema Cuplaj maxim in graf bipartit Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
/* 
 * File:   main.cpp
 * Author: virtualdemon
 *
 * Created on May 1, 2010, 5:21 PM
 */
#include <queue>
#include <cstdlib>
#include <fstream>
#include <algorithm>
#define Nmax 20011

/*
 * 
 */
using namespace std;
struct pr
{
    int y, c, flow;
    pr *next, *rit;
} *G[Nmax], *p[Nmax];
int f[Nmax];
int N, M, sink, source;
inline void add( int x, int y )
{
    pr* q=new pr;
    q->y=y; q->c=1;
    q->next=G[x];
    G[x]=q;
    pr* qq=new pr;
    qq->y=x; qq->c=qq->flow=q->flow=0;
    qq->next=G[y];
    G[y]=qq;
    G[x]->rit=G[y];
    G[y]->rit=G[x];
}
inline int find_path( void )
{
    int x;
    pr* q;
    queue< int > Q;
    fill( f+1, f+sink+1, -1 );
    for( Q.push(source); !Q.empty(); )
    {
        x=Q.front(); Q.pop();
        for( q=G[x]; q; q=q->next )
            if( ( q->c - q->flow ) > 0 && -1 == f[q->y] )
            {
                f[q->y]=x;
                p[q->y]=q;
                if( sink == q->y )
                {
                    for( x=sink; x; x=f[x] )
                        ++p[x]->flow, --p[x]->rit->flow;
                    return 1;
                }
                Q.push(q->y);
            }
    }
    return 0;
}
inline int MaxFlow( void )
{
    int s;
    for( s=0; find_path(); ++s );
    return s;
}
int main( void )
{
    pr* q;
    int E, x, y;
    ifstream in( "cuplaj.in" );
    for( in>>N>>M>>E; E; --E )
    {
        in>>x>>y;
        add( x, y+N+1 );
    }
    for( x=1; x <= N; ++x )
        if( G[x] )
            add( source, x );
    for( sink=N+M+2, y=1; y <= M; ++y )
        if( G[y+N+1] )
            add( y+N+1, sink );
    ofstream out( "cuplaj.out" );
    out<<(M=MaxFlow())<<'\n';
    for( x=1; M && x <= N; ++x )
    {
        for( q=G[x]; q; q=q->next )
            if( q->flow > 0  )
            {
                --M;
                out<<x<<' '<<( q->y-1-N )<<'\n';
                break;
            }
    }

    return EXIT_SUCCESS;
}