Cod sursa(job #3164367)

Utilizator cristiWTCristi Tanase cristiWT Data 2 noiembrie 2023 22:47:25
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>
#define int long long
using namespace std;

const int nmax = 2e5 + 5, mod = 1e9 + 7;
int n, m, k, cuplat[nmax], viz[nmax], crtviz;
vector<int> g[nmax];

void cupleaza(int x, int y) {
    cuplat[cuplat[x]] = cuplat[cuplat[y]] = 0;
    cuplat[x] = y;
    cuplat[y] = x;
}

bool dfs(int node) {
    viz[node] = crtviz;
    for (auto x: g[node])
        if (viz[x] < crtviz) {
            viz[x] = crtviz;
            if (cuplat[x]) {
                if (dfs(cuplat[x])) {
                    cupleaza(node, x);
                    return true;
                }
            } else {
                cupleaza(node, x);
                return true;
            }
        }
    return false;
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    freopen("cuplaj.in", "r", stdin);
    freopen("cuplaj.out", "w", stdout);


    cin >> n >> m >> k;
    for (int i = 1; i <= k; i++) {
        int x, y;
        cin >> x >> y;
        y += n;
        g[x].push_back(y);
        g[y].push_back(x);
    }

    bool ok = true;
    while (ok) {
        ok = false;
        crtviz++;
        for (int node = 1; node <= n; node++)
            if (!cuplat[node] && viz[node] < crtviz)
                ok |= dfs(node);
    }

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