Cod sursa(job #1384969)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 11 martie 2015 16:18:20
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 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 st[Nmax], dr[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 ( !dr[son] || dfs(dr[son]) )
        {
            st[nod] = son;
            dr[son] = nod;

            return true;
        }
    }

    return false;
}

void Hopcroft_Karp()
{
    bool changed = true;

    do
    {
        changed = false;

        memset(used, 0, sizeof(used));

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

    } while (changed);

    int matched = 0;

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

    ofstream out("cuplaj.out");

    out << matched << "\n";

    for (int i = 1; i <= N; ++i)
        if (st[i])
            out << i << " " << st[i] << "\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);
    }

    Hopcroft_Karp();
}