Cod sursa(job #579565)

Utilizator AndrewTheGreatAndrei Alexandrescu AndrewTheGreat Data 12 aprilie 2011 11:35:29
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <stdio.h>
#include <vector>
#include <string.h>
#define TR(C, i)\
    for(typeof ( C.begin() ) i = C.begin(); i != C.end(); i++)
#define pb push_back

using namespace std;

int N, M, E;
const int nmax = 10010;
vector <int> G[nmax];
bool U[nmax];
int R[nmax], L[nmax];

void read()
{
    freopen("cuplaj.in", "r", stdin);
    freopen("cuplaj.out", "w", stdout);

    scanf("%d %d %d", &N, &M, &E);
    int l, r;
    while(E--)
    {
        scanf("%d %d", &l, &r);
        G[l].pb( r );
    }
}

int PairUp(int x)
{
    if(U[x]) return 0;
    U[x] = true;

    TR(G[x], it)
        if(!R[*it] || PairUp(R[*it]))
        {
            L[x] = *it;
            R[*it] = x;
            return 1;
        }
    return 0;
}

int cuplaj()
{
    bool ok = true;
    int i, cuplu = 0;
    while( ok )
    {
        ok = false;
        memset(U, false, sizeof(U));

        for(i = 1; i <= N; i++)
            if(!L[i])
                if( PairUp(i) )
                {
                    ok = true;
                    cuplu++;
                }
    }
    return cuplu;
}

int main()
{
    read();
    printf("%d\n", cuplaj());
    for(int i = 1; i <= N; i++)
        if(L[i])
            printf("%d %d\n", i, L[i]);
    return 0;
}