Cod sursa(job #1394481)

Utilizator BLz0rDospra Cristian BLz0r Data 20 martie 2015 12:46:42
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <cstdio>
#include <vector>
#include <bitset>
using namespace std;

#define Nmax 10002
#define pb push_back

FILE *f = fopen ( "cuplaj.in", "r" );
FILE *g = fopen ( "cuplaj.out", "w" );

vector < int > G[Nmax];
bitset < Nmax > used;
int match1[Nmax], match2[Nmax];

int match ( int nod ){
    vector < int > :: iterator it;

    if ( used[nod] )
        return 0;

    used[nod] = 1;

    for ( it = G[nod].begin(); it < G[nod].end(); ++it ){
        if ( !match2[*it] ){
            match1[nod] = *it;
            match2[*it] = nod;
            return 1;
        }
    }

    for ( it = G[nod].begin(); it < G[nod].end(); ++it ){
        if ( match( match2[*it] ) ){
            match1[nod] = *it;
            match2[*it] = nod;
            return 1;
        }
    }
    return 0;
}

int main(){
    int N, M, E, x, y;

    fscanf ( f, "%d%d%d", &N, &M, &E );

    for ( int i = 1; i <= E; ++i ){
        fscanf ( f, "%d%d", &x, &y );
        G[x].pb ( y );
    }

    int schimb = 1;

    while ( schimb ){
        schimb = 0;
        used.reset();

        for ( int i = 1; i <= N; ++i ){
            if ( !match1[i] )
                schimb += match ( i );
        }

    }

    int matches = 0;

    for ( int i = 1; i <= N; ++i )
        if ( match1[i] )
            matches++;

    fprintf ( g, "%d\n", matches );

    for ( int i = 1; i <= N; ++i ){
        if ( match1[i] )
            fprintf ( g, "%d %d\n", i, match1[i] );
    }

    return 0;
}