Cod sursa(job #3328058)

Utilizator brianabucur11Briana Bucur brianabucur11 Data 6 decembrie 2025 01:07:48
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>
using namespace std;

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

const int nmax = 1e4 + 5;

vector <int> g[nmax];

int l[nmax], r[nmax], fr[nmax];
int n, m, e;

bool pairup (int node)
{
    if (fr[node])
        return false;
    fr[node] = 1;
    for (auto x : g[node])
    {
        if (!r[x])
        {
            l[node] = x;
            r[x] = node;
            return true;
        }
    }
    for (auto x : g[node])
    {
        if (pairup (r[x]))
        {
            l[node] = x;
            r[x] = node;
            return true;
        }
    }
    return false;
}

int main ()
{
    fin >> n >> m >> e;
    for (int i = 1; i <= e; i++)
    {
        int x, y;
        fin >> x >> y;
        g[x].push_back (y);
    }
    bool ok = true;
    while (ok)
    {
        ok = false;
        for (int i = 1; i <= n; i++)
            fr[i] = 0;
        for (int i = 1; i <= n; i++)
            if (!l[i])
                ok |= pairup (i);
    }
    int cuplaj = 0;
    for (int i = 1; i <= n; i++)
        cuplaj += l[i] > 0;
    fout << cuplaj << '\n';
    for (int i = 1; i <= n; i++)
        if (l[i] > 0)
            fout << i << " " << l[i] << '\n';
    return 0;
}