Cod sursa(job #1204484)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 3 iulie 2014 00:25:42
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <algorithm>

using namespace std;

const int Nmax = 1e4 + 2;

vector <int> G[Nmax];
int st[Nmax], dr[Nmax];
bool use[Nmax];

int N, M, E;

bool pairup( int nod )
{
    if ( use[nod] )
        return false;

    use[nod] = true;

    for ( auto x: G[nod] )
        if ( !dr[x] || pairup( dr[x] ))
        {
            st[nod] = x;
            dr[x] = nod;
            return true;
        }

    return false;
}

void Hopcroft_Karp()
{
    for ( int change = 1; change; )
    {
        change = 0;

        fill( use + 1, use + N + 1, 0 );

        for ( int i = 1; i <= N; ++i )
            if ( !st[i] )
                change |= pairup( i );
    }

    int match = 0;

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

    ofstream out("cuplaj.out");

    out << match << "\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, a, b; i <= E; ++i )
    {
        in >> a >> b;

        G[a].push_back( b );
    }

    Hopcroft_Karp();

    return 0;
}