Cod sursa(job #2952493)

Utilizator tifui.alexandruTifui Ioan Alexandru tifui.alexandru Data 9 decembrie 2022 13:45:20
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>

using namespace std;

const int Nmax = 10005;
vector <int> G[Nmax];

bool vis[Nmax];
int vL[Nmax];
int vR[Nmax];

bool match(int node) {
    if (vis[node])
        return false;
    vis[node] = true;

    for (int nei : G[node])
        if (!vL[nei]) {
            vL[nei] = node;
            vR[node] = nei;
            return true;
        }

    for (int nei : G[node]) 
        if (match(vL[nei])) {
            vL[nei] = node;
            vR[node] = nei;
            return true;
        }

    return false;
}

void romanian_match(int n) {
    bool can_match = true;
    while (can_match) {
        can_match = false;
        memset(vis, 0, sizeof(vis));

        for (int node = 1; node <= n; ++node)
            if (!vR[node] and match(node))
                can_match = true;
    }
}

int main() {
    string filename = "date";
    ifstream cin(filename + ".in");
    ofstream cout(filename + ".out");

    int n, m, e;
    cin >> n >> m >> e;
    while (e--) {
        int x, y;
        cin >> x >> y;
        G[x].push_back(y);
    }

    romanian_match(n);

    int match_size = 0;
    for (int node = 1; node <= n; ++node)
        if (vR[node])
            ++match_size;

    cout << match_size << '\n';
    for (int node = 1; node <= n; ++node)
        if (vR[node])
            cout << node << ' ' << vR[node] << '\n';

    return 0;
}