Cod sursa(job #3273439)

Utilizator cristiWTCristi Tanase cristiWT Data 2 februarie 2025 11:03:02
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
#include <bits/stdc++.h>
#define int long long
using namespace std;

const int nmax = 2e5, mod = 1e9 + 7, inf = 2e18;

signed main() {
    cin.tie(nullptr)->sync_with_stdio(false);
#ifdef LOCAL
    freopen("file.in", "r", stdin);
    freopen("file.out", "w", stdout);
#else
    freopen("cuplaj.in", "r", stdin);
    freopen("cuplaj.out", "w", stdout);
#endif

    int n, m, e;
    cin >> n >> m >> e;
    vector<vector<int>> g(n + m + 1);
    for (int i = 1; i <= e; i++) {
        int u, v; cin >> u >> v;
        v += n;
        g[u].push_back(v);
        g[v].push_back(u);
    }

    vector<int> cuplat(n + m + 1);
    vector<int> viz(n + m + 1);
    int crtviz = 1;
    function<int(int)> dfs = [&](int u) {
        viz[u] = crtviz;
        for (auto v: g[u]) {
            if (viz[v] == crtviz) continue;
            viz[v] = crtviz;
            if (cuplat[v]) {
                if (dfs(cuplat[v])) {
//                    cuplat[cuplat[u]] = cuplat[cuplat[v]] = 0;
                    cuplat[u] = v;
                    cuplat[v] = u;
                    return 1;
                }
            } else {
//                cuplat[cuplat[u]] = cuplat[cuplat[v]] = 0;
                cuplat[u] = v;
                cuplat[v] = u;
                return 1;
            }
        }
        return 0;
    };
    bool done = 0;
    while (!done) {
        done = 1;
        for (int i = 1; i <= n; i++) {
            if (!cuplat[i] && viz[i] < crtviz && dfs(i)) {
                done = 0;
            }
        }
        crtviz++;
    }

    int ans = 0;
    for (int i = 1; i <= n; i++) {
        if (cuplat[i]) ans++;
    }
    cout << ans << '\n';
    for (int i = 1; i <= n; i++) {
        if (cuplat[i]) {
            cout << i << ' ' << cuplat[i] - n << '\n';
        }
    }
}