Cod sursa(job #1387415)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 14 martie 2015 09:56:25
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <bits/stdc++.h>

using namespace std;

const int Nmax = 10000 + 1;
const int Mmax = 100000 + 1;

struct Edge
{
    int nod;
    int urm;
};

Edge G[2 * Mmax];
int head[Nmax];

bool used[Nmax];
int match[2 * Nmax];

int N, M, E, contor;

void addEdge(int x, int y)
{
    contor++;
    G[contor].nod = y;
    G[contor].urm = head[x];
    head[x] = contor;
}

bool dfs(int nod)
{
    if (used[nod])
        return false;

    used[nod] = true;

    for (int p = head[nod]; p; p = G[p].urm)
    {
        int son = G[p].nod;

        if ( !match[son] )
        {
            match[nod] = son;
            match[son] = nod;

            return true;
        }
    }

    for (int p = head[nod]; p; p = G[p].urm)
    {
        int son = G[p].nod;

        if ( dfs(match[son]) )
        {
            match[nod] = son;
            match[son] = nod;

            return true;
        }
    }

    return false;
}

void Hopcroft_Karp()
{
    bool changed = true;

    do
    {
        changed = false;

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

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

    } while (changed);

    int matched = 0;

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

    ofstream out("cuplaj.out");

    out << matched << "\n";

    for (int i = 1; i <= N; ++i)
        if (match[i])
            out << i << " " << match[i] - N << "\n";
}

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

    in >> N >> M >> E;

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

        addEdge(a, b + N);
    }

    Hopcroft_Karp();
}