Cod sursa(job #2371212)

Utilizator PaulTPaul Tirlisan PaulT Data 6 martie 2019 16:46:08
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

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

using VI = vector<int>;
using VVI = vector<VI>;
using VB = vector<bool>;

int n, m, E, max_matching;
VI L, R;
VVI G;
VB v;

void Read();
bool DoMatch(int x);

int main()
{
    Read();
    bool found_path;
    do
    {
        v = VB(n + 1);
        found_path = false;
        for (int x = 1; x <= n; x++)
            if (!L[x] && DoMatch(x))
            {
                found_path = true;
                max_matching++;
            }
    } while (found_path);

    fout << max_matching << '\n';
    for (int x = 1; x <= n; x++)
        if (L[x])
            fout << x << ' ' << L[x] << '\n';

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

bool DoMatch(int x)
{
    if (v[x]) return false;
    v[x] = true;
    for (const int& y : G[x])
        if (!R[y] || DoMatch(R[y]))
        {
            L[x] = y;
            R[y] = x;
            return true;
        }
    return false;
}

void Read()
{
    fin >> n >> m >> E;
    L = VI(n + 1);
    R = VI(m + 1);
    G = VVI(n + 1);
    int x, y;
    for (int i = 0; i < E; i++)
    {
        fin >> x >> y;
        G[x].push_back(y);
    }
}