Cod sursa(job #3148783)

Utilizator Maftei_TudorMaftei Tudor Maftei_Tudor Data 4 septembrie 2023 11:45:49
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <vector>

#define pb push_back

using namespace std;
ifstream in("cuplaj.in");
ofstream out("cuplaj.out");
const int N = 2e4 + 5;

int n, m, e, viz, vzt[N], cuplat[N];
vector<int> g[N];

void cupleaza(int a, int b) {
    cuplat[cuplat[a]] = 0;
    cuplat[a] = b;
    cuplat[cuplat[b]] = 0;
    cuplat[b] = a;
}

bool DFS(int nod) {
    vzt[nod] = viz;

    for(auto nxt : g[nod]) {
        if(vzt[nxt] < viz) {
            vzt[nxt] = viz;
            if(cuplat[nxt]) {
                if(DFS(cuplat[nxt])) {
                    cupleaza(nod, nxt);
                    return 1;
                }
            }
            else {
                cupleaza(nod, nxt);
                return 1;
            }
        }
    }

    return 0;
}

int main()
{
    in >> n >> m >> e;
    for(int i=1; i<=e; i++) {
        int x, y;
        in >> x >> y;
        y += n;
        g[x].pb(y);
        g[y].pb(x);
    }

    bool ok = 1;
    while(ok) {
        ok = 0;
        viz++;
        for(int i=1; i<=n+m; i++)
            if(!cuplat[i] && vzt[i] < viz) {
                ok |= DFS(i);
            }
    }

    int ans = 0;
    for(int i=1; i<=n; i++)
        ans += (cuplat[i] != 0);

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