Cod sursa(job #1537175)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 26 noiembrie 2015 23:33:53
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 10000 + 1;

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

int N, M, E;

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

    used[node] = true;

    for (auto v : G[node])
    {
        if (matched[v] == 0)
        {
            matched[node] = v;
            matched[v] = node;

            return true;
        }
    }

    for (auto v : G[node])
    {
        if (pairUp(matched[v]))
        {
            matched[node] = v;
            matched[v] = node;

            return true;
        }
    }

    return false;
}

void matching()
{
    ofstream out("cuplaj.out");

    int changed = 0;

    do
    {
        changed = 0;

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

        for (int i = 1; i <= N; ++i)
            if (matched[i] == 0)
                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.close();
}

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

    in >> N >> M >> E;

    for (int i = 1; i <= E; ++i)
    {
        int x, y;
        in >> x >> y;

        G[x].push_back(y + N);
    }

    matching();

    return 0;
}