Cod sursa(job #2819608)

Utilizator realmeabefirhuja petru realmeabefir Data 18 decembrie 2021 18:24:33
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <bits/stdc++.h>

#define siz 100005

using namespace std;

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

vector<int> la[siz];
int l[siz], r[siz], viz[siz];
int n1, n2, m;

int match(int from)
{
    if (viz[from])
        return 0;
    viz[from] = 1;

    for (auto& to: la[from])
    {
        if (r[to] == 0)
        {
            r[to] = from;
            l[from] = to;
            return 1;
        }
    }

    for (auto& to: la[from])
    {
        if (match(r[to]))
        {
            r[to] = from;
            l[from] = to;
            return 1;
        }
    }
    return 0;
}

int main()
{
    in >> n1 >> n2 >> m;
    while (m--)
    {
        int x,y;
        in >> x >> y;
        la[x].push_back(y);
    }

    int cuplaj = 0;
    while (true)
    {
        int opt = 0;
        memset(viz, 0, sizeof(int) * siz);
        for (int i = 1; i <= n1; i++)
        {
            if (l[i] == 0 && match(i))
            {
                opt = 1;
                cuplaj++;
            }
        }
        if (!opt)
            break;
    }

    out << cuplaj << '\n';
    for (int i = 1; i <= n1; i++)
    {
        if (l[i])
            out << i << ' ' << l[i] << '\n';
    }

    return 0;
}