Cod sursa(job #2587784)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 23 martie 2020 15:57:05
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <vector>
#include <fstream>

using std::vector;
std::ifstream fin("cuplaj.in");
std::ofstream fout("cuplaj.out");

bool match(int node, vector<vector<int>>& ad, vector<bool>& vis, vector<int>& matchR, vector<int>& matchL) {
    if (vis[node])
        return false;
    vis[node] = true;

    for (int nghb : ad[node])
        if (!matchL[nghb]) {
            matchR[node] = nghb;
            matchL[nghb] = node;
            return true;
        }
    for (int nghb : ad[node])
        if (match(matchL[nghb], ad, vis, matchR, matchL)) {
            matchR[node] = nghb;
            matchL[nghb] = node;
            return true;
        }
    return false;
}

int main() {
    int m, n, e;
    fin >> m >> n >> e;

    vector<vector<int>> ad(m + 1);
    for (int i = 0; i < e; i++) {
        int x, y; fin >> x >> y;
        ad[x].push_back(y);
    }

    vector<int> matchR(m + 1);
    vector<int> matchL(n + 1);

    bool toDo;
    do {
        toDo = false;
        vector<bool> vis(m + 1);
        for (int i = 1; i <= m; i++)
            if (!matchR[i])
                toDo |= match(i, ad, vis, matchR, matchL);
    } while (toDo);

    int matched = 0;
    for (int i = 1; i <= m; i++)
        matched += (bool) matchR[i];

    fout << matched << '\n';
    for (int i = 1; i <= m; i++)
        if (matchR[i])
            fout << i << ' ' << matchR[i] << '\n';

    fout.close();
    return 0;
}