Cod sursa(job #1976972)

Utilizator blatulInstitutul de Arta Gastronomica blatul Data 4 mai 2017 17:57:28
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <bits/stdc++.h>
using namespace std;

#define NMAX 10002

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

vector<int> graf[2 * NMAX];
bitset<2 * NMAX> used;

int matched[2 * NMAX];

bool pairUp(int node) {

    if (used[node])
        return false;

    used[node] = true;

    for (auto& adj: graf[node]) {
        if (!matched[adj]) {
            matched[node] = adj;
            matched[adj] = node;
            return true;
        }
    }

    for (auto& adj: graf[node]) {
        if (pairUp(matched[adj])) {
            matched[node] = adj;
            matched[adj] = node;
            return true;
        }
    }

    return false;
}


int main() {

    int N, M, E;

    fin >> N >> M >> E;

    int x, y;
    while (E--) {

        fin >> x >> y;

        y += N;

        graf[x].push_back(y);
        graf[y].push_back(x);
    }

    int changes = 1;

    while (changes != 0) {

        changes = 0;
        used.reset();

        for (int i = 1; i <= N; ++i) {
            if (!matched[i])
                changes += pairUp(i);
        }
    }

    vector< pair<int, int> > pairs;

    int nrMatches = 0;
    for (int i = 1; i <= N; ++i)
        if (matched[i])
            pairs.push_back(make_pair(i, matched[i] - N));

    fout << pairs.size() << "\n";
    for (auto& it: pairs)
        fout << it.first << " " << it.second << "\n";

    return 0;
}