Cod sursa(job #1736900)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 2 august 2016 21:09:53
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>

using namespace std;

constexpr int MAX_N = 10000 + 1;

vector<int> G[MAX_N];
int matched[MAX_N * 2];
int used[MAX_N * 2];

int N, M, E;

void addEdge(int x, int y)
{
    G[x].push_back(y + N);
}

bool pairUp(int node)
{
    if (used[node])
        return false;

    used[node] = true;

    for (int v : G[node])
        if (!matched[v])
        {
            matched[v] = node;
            matched[node] = v;
            return true;
        }

    for (int v : G[node])
        if (pairUp(matched[v]))
        {
            matched[v] = node;
            matched[node] = v;
            return true;
        }

    return false;
}

void Hopcroft_Karp(ostream &out)
{
    bool changed;

    do
    {
        changed = false;

        for (int i = 1; i <= N + M; ++i)
            used[i] = false;

        for (int i = 1; i <= N; ++i)
            if (!matched[i])
                changed |= pairUp(i);

    } while (changed);

    int card = 0;

    for (int i = 1; i <= N; ++i)
        card += matched[i] > 0;

    out << card << "\n";

    for (int i = 1; i <= N; ++i)
        if (matched[i] > 0)
            out << i << " " << matched[i] - N << "\n";

    out.flush();
}

int main()
{
    ifstream in("cuplaj.in");
    ofstream out("cuplaj.out");

    in >> N >> M >> E;

    for (int i = 1; i <= E; ++i)
    {
        int a, b;
        in >> a >> b;

        addEdge(a, b);
    }

    Hopcroft_Karp(out);

    return 0;
}