Cod sursa(job #1758208)

Utilizator preda.andreiPreda Andrei preda.andrei Data 16 septembrie 2016 19:38:40
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

#define NMAX 10001

vector<int> A[NMAX];
int vecinInA[NMAX];
int vecinInB[NMAX];
vector<bool> vizitat(NMAX);

bool cupleaza(int nod);

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

    int n, m, k;
    fin >> n >> m >> k;

    while (k--) {
        int x, y;
        fin >> x >> y;
        A[x].push_back(y);
    }

    bool cuplajNou;
    do {
        cuplajNou = false;

        for (int i = 1; i <= n; ++i) {
            if (vecinInB[i] == 0) {
                if (cupleaza(i)) {
                    cuplajNou = true;
                }
            }
        }

        if (cuplajNou) {
            for (int i = 1; i <= n; ++i)
                vizitat[i] = false;
        }

    } while (cuplajNou);

    int muchii = 0;
    for (int i = 1; i <= n; ++i)
        muchii += (vecinInB[i] != 0);

    fout << muchii << "\n";
    for (int i = 1; i <= n; ++i) {
        if (vecinInB[i]) {
            fout << i << " " << vecinInB[i] << "\n";
        }
    }

    return 0;
}

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

    for (int v : A[nod]) {
        if (vecinInA[v] == 0) {
            vecinInB[nod] = v;
            vecinInA[v] = nod;
            return true;
        }
    }

    for (int v : A[nod]) {
        if (cupleaza(vecinInA[v])) {
            vecinInB[nod] = v;
            vecinInA[v] = nod;
            return true;
        }
    }
    return false;
}