Cod sursa(job #3348735)

Utilizator stefan_dore_Stefan Dore stefan_dore_ Data 23 martie 2026 19:00:07
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

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

const int NMAX = 10000;

vector<int> G[NMAX+1];
int N, M, E,
    L[NMAX+1], R[NMAX+1],
    maxMatch;
bool viz[NMAX+1];


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

bool DFS(int x) {
    if (viz[x]) return 0;
    viz[x] = 1;
    //
    for (const auto &y : G[x])
        if (!R[y] || DFS(R[y])) {
            L[x] = y;
            R[y] = x;
            return 1;
        }
    //
    return 0;
}

void HK() { /// Hopcroft-Karp
    bool wasChanged = 1;
    while(wasChanged) {
        wasChanged = 0;
        //
        for (int i=1; i<=N; i++)
            viz[i] = 0;
        //
        for(int i=1; i<=N; i++)
            if(!L[i] && DFS(i)) {
                wasChanged = 1;
                maxMatch++;
            }
    }
}

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