Cod sursa(job #3325049)

Utilizator vlad2009Vlad Tutunaru vlad2009 Data 24 noiembrie 2025 16:27:17
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/extc++.h>

using namespace std;

typedef long long ll;

const int N = 2e4 + 7;

vector<int> g[N];
bool vis[N];
int who[N];

bool try_pair(int u) {
    vis[u] = true;
    for (auto v : g[u]) {
        if (who[v] == -1) {
            who[v] = u;
            who[u] = v;
            return true;
        }
    }
    for (auto v : g[u]) {
        if (vis[v]) continue;
        vis[v] = 1;
        if (try_pair(who[v])) {
            who[v] = u;
            who[u] = v;
            return true;
        }
    }
    return false;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    freopen("cuplaj.in", "r", stdin);
    freopen("cuplaj.out", "w", stdout);
    int nl, nr, e;
    cin >> nl >> nr >> e;
    for (int i = 0; i < e; ++i) {
        int u, v;
        cin >> u >> v;
        g[u].push_back(v + nl);
        g[v + nl].push_back(u);
    }
    
    for (int i = 1; i <= nl + nr; ++i) {
        who[i] = -1;
    }
    bool ok = 1;
    while (ok) {
        ok = false;
        for (int i = 1; i <= nl + nr; ++i) {
            vis[i] = false;
        }
        for (int i = 1; i <= nl; ++i) {
            if (!vis[i] && who[i] == -1) {
                ok |= try_pair(i);
            }
        }
    }
    vector<pair<int, int>> edges;
    for (int i = 1; i <= nl; ++i) {
        if (who[i] != -1) {
            edges.push_back(make_pair(i, who[i] - nl)); 
        }
    }
    cout << edges.size() << "\n";
    for (auto [a, b] : edges) cout << a << " " << b << "\n";
    return 0;
}