Cod sursa(job #2855465)

Utilizator chriss_b_001Cristian Benghe chriss_b_001 Data 22 februarie 2022 14:55:32
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 10001;

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

vector <int> G[NMAX];
int N, M, E,
    L[NMAX], R[NMAX], ///cuplaje realizate in ambele sensuri
    maxMatch;

bool viz[NMAX]; ///noduri folosite intr o iteratie

void citire()
{
    int x, y;
    f >> N >> M >> E;
    while(E--)
    {
        f >> x >> y;
        G[x].push_back(y);
    }
}

bool match(int x)
{
    if(viz[x])return 0; ///daca a mai fost folosit in iteratia curenta, ne intoarcem
    viz[x] = 1;
    for(auto &y : G[x])
        if(R[y] == 0) ///incercam sa-l cuplam cu un nod adiacent
        {
            L[x] = y;
            R[y] = x;
            return 1;
        }
    for(auto &y : G[x])
        if(match(R[y])) ///incercam a 2-a oara sa eliberam un nod adiacent ocupat
        {
            L[x] = y;
            R[y] = x;
            return 1;
        }
    return 0;
}

void HK()
{
    bool wasChanged = 1;
    int i;
    while(wasChanged) ///cat timp s-a facut o cuplare in iteratia anterioara => este posibil sa mai putem cupla
    {
        wasChanged = 0;
        for(i = 1; i <= N; ++i)
            viz[i] = 0;
        for(i = 1; i <= N; ++i)
            if(!L[i] && match(i))
            {
                wasChanged = 1;
                ++maxMatch;
            }
    }
}

int main()
{
    citire();
    HK();
    g << maxMatch << '\n';
    for(int i = 1; i <= N; ++i) ///scriem cuplajele
    {
        if(L[i] != 0)
            g << i << ' ' << L[i] << '\n';
    }


    return 0;
}