Cod sursa(job #1357096)

Utilizator Ionut228Ionut Calofir Ionut228 Data 23 februarie 2015 19:23:55
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

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

int N, M, E;
int cuplaj;
int L[10005], R[10005];
vector<int> V[10005];
bool used[10005];

bool cupleaza(int nod)
{
    if (used[nod])
        return false;
    used[nod] = true;

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

    for (vector<int>::iterator it = V[nod].begin(); it != V[nod].end(); ++it) // incerc sa cuplez R[*it] cu un alt nod
    {
        if (cupleaza(R[*it])) // pot sa-l cuplez deci *it o sa fie liber acum
        {
            L[nod] = *it;
            R[*it] = nod;
            return true;
        }
    }

    return false;
}

int main()
{
    fin >> N >> M >> E;
    for (int i = 1, nod1, nod2; i <= E; ++i)
    {
        fin >> nod1 >> nod2;
        V[nod1].push_back(nod2);
    }

    bool change  = true;
    while (change)
    {
        change = false;
        memset(used, false, sizeof(used));

        for (int i = 1; i <= N; ++i)
            if (!L[i])
                if (cupleaza(i))
                    change = true;
    }

    for (int i = 1; i <= N; ++i)
        if (L[i])
            ++cuplaj;

    fout << cuplaj << '\n';
    for (int i = 1; i <= N; ++i)
        if (L[i])
            fout << i << ' ' << L[i] << '\n';

    fin.close();
    fout.close();
    return 0;
}