Cod sursa(job #1165719)

Utilizator poptibiPop Tiberiu poptibi Data 2 aprilie 2014 21:08:04
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;

const int NMAX = 10010;

int N, M, E, X, Y, L[NMAX], R[NMAX];
bool Used[NMAX];
vector<int> G[NMAX];

bool PairUp(int Node)
{
    if(Used[Node]) return 0;
    Used[Node] = 1;

    for(vector<int> :: iterator it = G[Node].begin(); it != G[Node].end(); ++ it)
        if(!R[*it])
        {
            L[Node] = *it;
            R[*it] = Node;
            return 1;
        }

    for(vector<int> :: iterator it = G[Node].begin(); it != G[Node].end(); ++ it)
        if(PairUp(R[*it]))
        {
            L[Node] = *it;
            R[*it] = Node;
            return 1;
        }
    return 0;
}

void MaxMatching()
{
    bool OK = 1;
    while(OK)
    {
        OK = 0;
        for(int i = 1; i <= N; ++ i) Used[i] = 0;
        for(int i = 1; i <= N; ++ i)
            if(!L[i] && PairUp(i))
                OK = 1;
    }

    int Ans = 0;
    for(int i = 1; i <= N; ++ i) Ans += L[i] > 0;

    printf("%i\n", Ans);
    for(int i = 1; i <= N; ++ i)
        if(L[i])
            printf("%i %i\n", i, L[i]);
}

int main()
{
    freopen("cuplaj.in", "r", stdin);
    freopen("cuplaj.out", "w", stdout);

    scanf("%i %i %i", &N, &M, &E);
    for(int i = 1; i <= E; ++ i)
    {
        scanf("%i %i", &X, &Y);
        G[X].push_back(Y);
    }

    MaxMatching();
}