Cod sursa(job #3170331)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 17 noiembrie 2023 14:00:11
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 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 match[2 * nmax + 5]{ 0 };

bool used[nmax + 5]{ 0 };

bool find_paths(int u) {
    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 (!match[v] || (not used[match[v]] && find_paths(match[v]))) {
            match[u] = v, match[v] = u;
            return true;
        }
    }
    return false;
}

int matching() {
    bool good = true; // exista drumuri de augumentare
    int cnt = 0;
    while (good) {
        good = false;
        memset(used, false, (n + 1) * sizeof(bool));
        for (int u = 1; u <= n; ++u) {
            // `u` nu are pereche si am gasit un drum de augumentare din acesta
            if (!match[u] && find_paths(u)) {
                good = true;
                cnt++;
            }
        }
    }
    return cnt;
}

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);
        // cuplam cele 2 noduri daca nu sunt cuplate
        if (!match[u] && !match[v]) {
            match[u] = v, match[v] = u;
        }
    }
    fout << matching() << nl;
    for (int u = 1; u <= n; ++u) {
        if (match[u]) {
            fout << u << sp << match[u] - n << nl;
        }
    }
}