Cod sursa(job #2882820)

Utilizator Davla2Stancu Vlad Davla2 Data 31 martie 2022 20:15:20
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;

const int N = 1e4;

vector <int> a1[N+1], a2[N+1];
int n1, n2, m, pereche1[N+1], pereche2[N+1];
bitset <N+1> viz;

int caut_pereche(int x1)
{
    if (viz[x1])
    {
        return 0;
    }
    viz[x1] = 1;
    for (auto x2: a1[x1])
    {
        if (pereche2[x2] == 0 || caut_pereche(pereche2[x2]))///x2 nu e cuplat sau perechea sa poate fi cuplata altfel
        {
            pereche1[x1] = x2;
            pereche2[x2] = x1;
            return x2;
        }
    }
    return 0;
}

int main()
{
    ifstream in("cuplaj.in");
    ofstream out("cuplaj.out");
    in >> n1 >> n2 >> m;
    for (int i = 0; i < m; i++)
    {
        int x1, x2;
        in >> x1 >> x2;
        a1[x1].push_back(x2);
        a2[x2].push_back(x1);
    }
    in.close();
    bool cresc;
    do
    {
        cresc = false;
        viz.reset();
        for (int x1 = 1; x1 <= n1; x1++)
        {
            if (pereche1[x1] == 0)///x1 nu este cuplat
            {
                pereche1[x1] = caut_pereche(x1);
                if (pereche1[x1] != 0)
                {
                    cresc = true;///cuplajul s-a marit
                }
            }
        }
    }
    while (cresc);
    int cuplaj = 0;
    for (int x1 = 1; x1 <= n1; x1++)
    {
        if (pereche1[x1] != 0)
        {
            cuplaj++;
        }
    }
    out << cuplaj << "\n";
    for (int x1 = 1; x1 <= n1; x1++)
    {
        if (pereche1[x1] != 0)
        {
            out << x1 << " " << pereche1[x1] << "\n";
        }
    }
    out.close();
    return 0;
}