Cod sursa(job #1756602)

Utilizator Theodor1000Cristea Theodor Stefan Theodor1000 Data 13 septembrie 2016 09:27:31
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <cstdio>
#include <algorithm>
#include <vector>

using namespace std;

vector <int> v[10010];
int lf[10010], rg[10010];
bool ap[10010];

inline int cupleaza (int nod)
{
    if (ap[nod]) return 0;
    ap[nod] = true;

    for (auto &it : v[nod])
        if (!rg[it])
        {
            lf[nod] = it;
            rg[it] = nod;

            return 1;
        }

    for (auto &it : v[nod])
        if (cupleaza (rg[it]))
        {
            lf[nod] = it;
            rg[it] = nod;

            return 1;
        }

    return 0;
}

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

    int n, m, e;
    scanf ("%d %d %d", &n, &m, &e);

    for (; e; --e)
    {
        int x, y;
        scanf ("%d %d", &x, &y);
        v[x].push_back (y);
    }

    for (int OK = 1; OK;)
    {
        OK = 0;

        for (int i = 1; i <= n; ++i)
            ap[i] = false;

        for (int i = 1; i <= n; ++i)
            if (!lf[i]) OK += cupleaza (i);
    }

    int nr = 0;
    for (int i = 1; i <= n; ++i)
        nr += (lf[i] > 0);

    printf ("%d\n", nr);

    for (int i = 1; i <= n; ++i)
        if (lf[i]) printf ("%d %d\n", i, lf[i]);

    return 0;
}