Cod sursa(job #2174946)

Utilizator dragomirmanuelDragomir Manuel dragomirmanuel Data 16 martie 2018 14:23:51
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>

#define pb push_back

using namespace std;

const int NMax = 10005;

int N, M, E;
int viz[NMax], Left[NMax], Right[NMax];

vector < int > G[NMax];

void Read()
{
    scanf("%d %d %d\n", &N, &M, &E);

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

int cuplaj(int nod)
{
    if(viz[nod])
        return 0;

    viz[nod] = 1;

    for(auto it: G[nod])
        if(!Left[it])
        {
            Left[it] = nod;
            Right[nod] = it;
            return 1;
        }

    for(auto it: G[nod])
        if(cuplaj(Left[it]))
        {
            Right[nod] = it;
            Left[it] = nod;
            return 1;
        }

    return 0;
}

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

    Read();
    int OK = 1;

    while(OK)
    {
        memset(viz,0,sizeof(viz));
        OK = 0;

        for(int i=1; i<=N; ++i)
            if(!Right[i])
                OK += cuplaj(i);
    }

    int nr = 0;
    for(int i=1; i<=N; ++i)
        if(Right[i])
            ++nr;

    cout << nr << "\n";

    for(int i=1; i<=N; ++i)
        if(Right[i])
            cout << i << " " << Right[i] << "\n";
    return 0;
}