Cod sursa(job #1369563)

Utilizator teo.serbanescuTeo Serbanescu teo.serbanescu Data 3 martie 2015 09:45:05
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>
#include <vector>
#include <string.h>

using namespace std;

fstream f("cuplaj.in",ios::in);
fstream g("cuplaj.out",ios::out);

const int nmax = 10010;

vector <int> a[nmax];

int n, m, e, i, x, y, l[nmax], r[nmax], used[nmax], change, cuplaj;

void read()
{
    f >> n >> m >> e;
    for (i = 1; i <= e; i++)
    {
        f >> x >> y;
        a[x].push_back(y);
    }
}

int couple(int nc)
{
    if (used[nc]) return 0;
    used[nc] = 1;
    for (vector <int>::iterator it = a[nc].begin(); it != a[nc].end(); ++it)
        if (!r[*it])
        {
            l[nc] = *it;
            r[*it] = nc;
            return 1;
        }
    for (vector <int>::iterator it = a[nc].begin(); it != a[nc].end(); ++it)
        if (couple(r[*it]))
        {
            l[nc] = *it;
            r[*it] = nc;
            return 1;
        }
    return 0;
}
int main()
{
    read();
    change = 1;
    while (change)
    {
        change = 0;
        memset(used, 0, sizeof(used));
        for (i = 1; i <= n; i++)
            if (!l[i])
            {
                if (couple(i)) change = 1;
            }
    }
    for (i = 1; i <= n; i++) if (l[i]) cuplaj++;
    g << cuplaj << '\n';
    for (i = 1; i <= n; i++) if (l[i]) g << i << " " << l[i] << '\n';
    return 0;
}