Cod sursa(job #2956390)

Utilizator YosifIosif Andrei Stefan Yosif Data 19 decembrie 2022 14:20:52
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <bits/stdc++.h> 
using namespace std;

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

int n, m, k;
vector <int> g[10001];
int d[10001], pairX[10001], pairY[10001];
const int inf = 1000000000;

bool bfs()
{
    queue <int> Q;

    d[0] = inf;

    for (int i = 1; i <= n; i++)
        if (!pairX[i])
            d[i] = 0, Q.push(i);
        else
            d[i] = inf;

    while (!Q.empty())
    {
        int nod = Q.front();
        Q.pop();

        if (d[nod] >= d[0])
            continue;

        for (auto& i : g[nod])
            if (d[pairY[i]] > d[nod] + 1)
            {
                d[pairY[i]] = d[nod] + 1;
                Q.push(pairY[i]);
            }
    }

    return d[0] != inf;
}

bool dfs(int nod)
{
    if (!nod)
        return true;

    for (auto& i : g[nod])
        if (d[pairY[i]] == d[nod] + 1 && dfs(pairY[i]))
        {
            pairX[nod] = i;
            pairY[i] = nod;
            return true;
        }

    return false;
}

int main() {

    fin >> n >> m >> k;

    for (int i = 1; i <= k; i++)
    {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
    }

    int nr = 0;

    while (bfs())
        for (int i = 1; i <= n; i++)
            if (!pairX[i] && dfs(i))
                nr++;

    fout << nr << '\n';

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

    return 0;
}