Cod sursa(job #3302638)

Utilizator BuzdiBuzdugan Rares Andrei Buzdi Data 9 iulie 2025 16:50:11
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>

#define ll long long
#define ull unsigned long long
#define ld long double

using namespace std;
using namespace __gnu_pbds;

typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;

ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

const int NMAX = 1e4;

int n1, n2, m;
vector<int> g[NMAX + 1];
vector<pair<int, int>> answer;
int l[NMAX + 1], r[NMAX + 1], visited[NMAX + 1];

bool pairup(int node) {
    if (visited[node]) {
        return false;
    }
    visited[node] = 1;
    for (int next_node : g[node]) {
        if (!r[next_node]) {
            l[node] = next_node;
            r[next_node] = node;
            return true;
        }
    }

    for (int next_node : g[node]) {
        if (pairup(r[next_node])) {
            l[node] = next_node;
            r[next_node] = node;
            return true;
        }
    }
    return false;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    fin >> n1 >> n2 >> m;
    for(int i = 1; i <= m; i++) {
        int a, b;
        fin >> a >> b;
        g[a].push_back(b);
    }

    bool changed = true;
    while (changed) {
        changed = false;
        for (int i = 1; i <= n1; i++) {
            visited[i] = 0;
        }
        for (int i = 1; i <= n1; i++) {
            if (!l[i]) {
                changed |= pairup(i);
            }
        }
    }

    for (int i = 1; i <= n1; i++) {
        if (l[i] > 0) {
            answer.emplace_back(i, l[i]);
        }
    }

    fout << answer.size() << '\n';
    for (auto [x, y] : answer) {
        fout << x << ' ' << y << '\n';
    }

    return 0;
}