Cod sursa(job #3170324)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 17 noiembrie 2023 13:47:15
Problema Cuplaj maxim in graf bipartit Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.07 kb
#include <bits/stdc++.h>
#include <random>
#include <chrono>
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const char nl = '\n';
const char sp = ' ';
const int inf = 0x3f3f3f3f;
const long long INF = 1000000000000000000;
const int mod = 1e9 + 7;
const char out[2][4]{ "NO", "YES" };
#define all(a) a.begin(), a.end()
using ll = long long;
ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

#define variableName(var) #var
#define __debug(var) cout << #var << " = " << var << '\n'
inline int rint(int a, int b) { return uniform_int_distribution<int>(a, b)(rng); }

const int nmax = 1e4;

int n, m, e;
vector<int> g[2 * nmax + 5];
int pa[nmax + 5]{ 0 }, pb[nmax + 5]{ 0 };
// pa[u] = perechea nodului `u` din A in B
// pb[v] = perechea nodului `v` din B in A

bool used[2 * nmax + 5]{ 0 };

bool find_paths(int u) {
    if (used[u]) {
        return false;
    }
    used[u] = true;
    for (auto& v : g[u]) {
        // putem forma un drum de augumentare de lungime 1
        // sau putem inversa un drum de augumentare curent
        if (!pb[v] || find_paths(pb[v])) {
            pa[u] = v, pb[v] = u;
            return true;
        }
    }
    return false;
}

void matching() {
    bool good = false;
    while (!good) {
        good = true;
        memset(used, false, (n + m + 1) * sizeof(bool));
        for (int i = 1; i <= n; ++i) {
            if (!pa[i]) {
                good |= !find_paths(i);
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    fin >> n >> m >> e;
    for (int i = 1; i <= e; ++i) {
        int u, v;
        fin >> u >> v;
        v += n;
        g[u].push_back(v);
        g[v].push_back(u);
        // adaug din start muchii daca pot
        if (!pa[u] && !pb[v]) {
            pa[u] = v, pb[v] = u;
        }
    }
    matching();
    fout << n - count(pa + 1, pa + n + 1, 0) << nl;
    for (int i = 1; i <= n; ++i) {
        if (pa[i]) {
            fout << i << sp << pa[i] - n << nl;
        }
    }
}