Cod sursa(job #2905372)

Utilizator BeilandArnoldArnold Beiland BeilandArnold Data 21 mai 2022 09:51:46
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>

using namespace std;

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

vector <int> G[10005];
int l[10005], r[10005], u[10005];


int pairup(int n)
{
    if (u[n])
      return 0;

    u[n] = 1;

    for (auto i = G[n].begin(); i != G[n].end(); i++)
        if (!r[*i])
        {
            l[n] = *i;
            r[*i] = n;
            return 1;
        }

    for (auto i = G[n].begin(); i != G[n].end(); i++)
        if (pairup(r[*i]))
        {
            l[n] = *i;
            r[*i] = n;
            return 1;
        }

    return 0;
}



int main()
{
    int n, m, cnt_edges;
    fin >> n >> m >> cnt_edges;

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

    int change = 1;

    while (change)
    {
        change = 0;
        memset(u, 0, sizeof(u));

        for (int i = 1; i <= n; i++)
            if (!l[i])
                change |= 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;
}