Cod sursa(job #2736322)

Utilizator MocalinnoMoca Andrei Catalin Mocalinno Data 3 aprilie 2021 12:53:17
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <bits/stdc++.h>
using namespace std;
void DAU(const string& task = "") {
    if (!task.empty())
        freopen((task + ".in").c_str(), "r", stdin),
        freopen((task + ".out").c_str(), "w", stdout);
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
}
void PLEC() {
    exit(0);
}
using VI   = vector<int>;
using VVI  = vector<VI>;
using VB   = vector<bool>;
using PII  = pair<int, int>;
using VPII  = vector<PII>;
class Cuplaj_Maxim {
public:
    Cuplaj_Maxim() {}
    Cuplaj_Maxim(const int& _n, const int& _m)
        : n(_n), m(_m), lm(_m + 1), rm(_n + 1), g(_n + 1), viz(_n + 1) {}
    inline void AddEdge(const int& x, const int& y) {
        g[x].emplace_back(y);
    }
    inline VPII Cuplaje() {
        bool can = true;
        while (can) {
            can = false;
            fill(viz.begin(), viz.end(), false);
            for (int i = 1; i <= n; ++i)
                if (!rm[i] && DFS(i))
                    can = true;
        }
        VPII res;
        for (int i = 1; i <= n; ++i)
            if (rm[i])
                res.emplace_back(i, rm[i]);
        return res;
    }
private:
    inline bool DFS(const int& x) {
        if (viz[x])
            return false;
        viz[x] = true;
        for (const int& y : g[x])
            if (!lm[y] || DFS(lm[y])) {
                lm[y] = x;
                rm[x] = y;
                return true;
            }
        return false;
    }
    int n, m;
    VI lm, rm;
    VVI g;
    VB viz;
};
int n, m, k, x, y;
signed main() {
    DAU("cuplaj");
    cin >> n >> m >> k;
    Cuplaj_Maxim graph(n, m);
    while (k--) {
        cin >> x >> y;
        graph.AddEdge(x, y);
    }
    VPII res = graph.Cuplaje();
    cout << res.size() << '\n';
    for (const PII& P : res)
        cout << P.first << ' ' << P.second << '\n';
    PLEC();
}