Cod sursa(job #2595138)

Utilizator PetrescuAlexandru Petrescu Petrescu Data 7 aprilie 2020 11:28:30
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <bits/stdc++.h>
#define MAX 10000

using namespace std;

vector<int>graph[MAX + 5];
int cuplajLeft[MAX + 5], cuplajRight[MAX + 5];
bool viz[MAX + 5];
int n, m, e;

bool cuplaj(int nod)
{
    if(viz[nod])
        return false;

    viz[nod] = 1;

    for(auto vecin : graph[nod])
        if(!cuplajLeft[vecin])
        {
            cuplajRight[nod] = vecin;
            cuplajLeft[vecin] = nod;

            return true;
        }

    for(auto vecin : graph[nod])
        if(cuplaj(cuplajLeft[vecin]))
        {
            cuplajRight[nod] = vecin;
            cuplajLeft[vecin] = nod;

            return true;
        }

    return false;
}
int main()
{
    ifstream fin("cuplaj.in");
    ofstream fout("cuplaj.out");

    ios::sync_with_stdio(false);
    fin.tie(0);
    fout.tie(0);

    fin >> n >> m >> e;

    for(int i = 1; i <= e; i++)
    {
        int a, b;

        fin >> a >> b;

        graph[a].push_back(b);
    }

    bool semafor;
    int sol = 0;

    do
    {
        semafor = false;

        memset(viz, 0, sizeof(viz));
        for(int nod = 1; nod <= n; nod++)
            if(!cuplajRight[nod] && cuplaj(nod))
                semafor = true;
    }while(semafor);

    for(int i = 1; i <= n; i++)
        if(cuplajRight[i])
            sol++;

    fout << sol << '\n';

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

    fin.close();
    fout.close();

    return 0;
}