Cod sursa(job #2419022)

Utilizator LeVladzCiuperceanu Vlad LeVladz Data 7 mai 2019 15:07:15
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

int n,m,e,i,x,y,f[10005],sol;
int Left[10005],Right[10005];
vector<int> L[10005];

int cupleaza(int nod)
{
    ///incerc sa il cuplez pe nod cu unul din cealalta multime
    if (f[nod] != 0)
        return 0;
    f[nod] = 1;
    for (int i=0; i<L[nod].size(); i++)
    {
        int vecin = L[nod][i];
        if (Right[vecin] == 0)
        {
            Left[nod] = vecin;
            Right[vecin] = nod;
            sol++;
            return 1;
        }
    }
    for (int i=0; i<L[nod].size(); i++)
    {
        int vecin = L[nod][i];
        if (cupleaza(Right[vecin]) == 1)
        {
            Left[nod] = vecin;
            Right[vecin] = nod;
            return 1;
        }
    }
    return 0;
}

int main()
{
    fin >> n >> m >> e;
    for (i=1; i<=e; i++)
    {
        fin >> x >> y;
        L[x].push_back(y);
    }
    ///left[i] = cel din dreapta cu care este cuplat i sau 0 daca e necuplat
    ///right[i] = cel din stanga cu care este cuplat i sau 0 daca e necuplat
    int ok = 0;
    do
    {
        ok = 0;
        for (i=1; i<=max(n, m); i++)
            f[i] = 0;
        for (i=1; i<=n; i++)
            if (Left[i] == 0)
                ok = max(ok, cupleaza(i));
    }while (ok == 1);
    fout << sol << "\n";
    for (i=1; i<=n; i++)
        if (Left[i] != 0)
            fout << i << " " << Left[i] << "\n";
    return 0;
}