Cod sursa(job #2832605)

Utilizator enestianEne Sebastian enestian Data 13 ianuarie 2022 23:01:23
Problema Cuplaj maxim in graf bipartit Scor 40
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 2.34 kb
//https://infoarena.ro/problema/cuplaj
//pseudocod algoritm din https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm
//o sursa ajutatoare pentru pseudocod https://infoarena.ro/job_detail/2818419?action=view-source
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream f("cuplaj.in");
ofstream g("cuplaj.out");
#define Nmax 100000
#define NIL 0
#define oo 100000
int N, M, E;
vector<int> Adj[Nmax];
vector <int> Pair_U;
vector <int> Pair_V;
vector <int> Dist;

bool BFS_Hopcroft_Karp()
{
    queue<int> Q;
    for (int u = 1; u <= N; u++)
    {
        if (Pair_U[u] == NIL)
        {
            Dist[u] = 0;
            Q.push(u);
        }
        else Dist[u] = oo;
    }
    Dist[NIL] = oo;

    while (Q.empty()==false)
    {
        int u = Q.front();
        Q.pop();
        if (Dist[u] < Dist[NIL])
        {
            for (auto v : Adj[u])
            {
                if (Dist[Pair_V[v]] == oo)
                {
                    Dist[Pair_V[v]] = Dist[u] + 1;
                    Q.push(Pair_V[v]);
                }
            }
        }
    }
    return (Dist[NIL] != oo);
}


bool DFS_Hopcroft_Karp(int u)
{
    if (u != NIL)
    {
        for (auto v : Adj[u])
        {
            if (Dist[Pair_V[v]] == Dist[u] + 1)
            {
                if (DFS_Hopcroft_Karp(Pair_V[v]) == true)
                {
                    Pair_V[v] = u;
                    Pair_U[u] = v;
                    return true;
                }
            }
        }
        Dist[u] = oo;
        return false;
    }
    return true;
}

void cuplaj_Hopcroft_Karp()
{
    Pair_U.resize(N+1, NIL);
    Pair_V.resize(M+1, NIL);
    Dist.resize(E+1, NIL);
    int matching = 0;

    while (BFS_Hopcroft_Karp()==true)
    {
        for (int i = 1; i <= N; i++)
            if (Pair_U[i] == NIL && (DFS_Hopcroft_Karp(i)==true))
                matching++;
    }

    ///Partea de afisare
    g << matching << "\n";
    for (int i = 1; i <= M; i++)
        g << Pair_V[i] << " " << i << "\n";
    f.close();
    g.close();
}

int main()
{
    int x, y;
    //citire
    f >> N >> M >> E;
    for (int i = 1; i <= E; i++) {
        f >> x >> y;
        Adj[x].push_back(y);
    }


    cuplaj_Hopcroft_Karp();
	
	return 0;
}