Cod sursa(job #2990531)

Utilizator amcbnCiobanu Andrei Mihai amcbn Data 8 martie 2023 00:29:54
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
/// [A][M][C][B][N] ///
#include <bits/stdc++.h>
const char nl = '\n';
const char sp = ' ';
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
using namespace std;
ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

const int nmax = 1e4;
int n, m, t;
vector<int> g[nmax + 1];
int p[nmax + 1]{0}; // size m
// nodul pereche din multimea L
int q[nmax + 1]{0}; // size n
// nodul pereche din multimea R
bool used[nmax + 1]{0}; // size n
// am folosit deja nodul din multimea R in cuplaj

bool dfs(int v) {
    used[v] = 1;
    for (int& u : g[v]) {
        if (!p[u] || (!used[p[u]] && dfs(p[u]))) {
            p[u] = v, q[v] = u;
            return 1;
        }
    }
    return 0;
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    fin >> n >> m >> t;
    while (t--) {
        int v, u;
        fin >> v >> u;
        g[v].push_back(u);
    }
    int cnt = 0, ok = 1;
    while (ok) {
        ok = 0;
        memset(used, 0, (n + 1) * sizeof(bool));
        for (int v = 1; v <= n; ++v) {
            if (!q[v] && dfs(v)) {
                cnt++;
                ok = 1;
            }
        }
    }
    fout << cnt << nl;
    for (int i = 1; i <= n; ++i) {
        if (q[i]) {
            fout << i << sp << q[i] << nl;
        }
    }
}