Cod sursa(job #2451703)

Utilizator andreiomd1Onut Andrei andreiomd1 Data 27 august 2019 20:20:38
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

ifstream f("cuplaj.in");
ofstream g("cuplaj.out");

const int NMAX = 1e4 + 5;

int N, M, E, X, Y;

int L[NMAX], R[NMAX];

bool Marked[NMAX];

vector < int > G[NMAX];

vector < pair < int, int > > Sol;

static inline void Read ()
{
    f.tie(NULL);

    f >> N >> M >> E;

    for(int i = 1; i <= E; ++i)
    {
        f >> X >> Y;

        G[X].push_back(Y);
    }

    return;
}

static inline bool Cupleaza (int Node)
{
    Marked[Node] = true;

    for(auto it : G[Node])
        if(!R[it])
        {
            L[Node] = it;

            R[it] = Node;

            return true;
        }

    for(auto it : G[Node])
        if(!Marked[R[it]])
            if(Cupleaza(R[it]))
            {
                L[Node] = it;

                R[it] = Node;

                return true;
            }

    return false;
}

static inline void Solve ()
{
    bool Done = true;

    while(Done)
    {
        Done = false;

        memset(Marked, false, sizeof(Marked));

        for(int i = 1; i <= N; ++i)
            if(!Marked[i])
                if(!L[i])
                    Done |= Cupleaza(i);
    }

    return;
}

static inline void Write ()
{
    int ans = 0;

    for(int i = 1; i <= N; ++i)
        if(L[i])
        {
            ++ans;

            Sol.push_back({i, L[i]});
        }

    g << ans << '\n';

    for(auto it : Sol)
        g  << it.first << ' ' << it.second << '\n';

    return;
}

int main()
{
    Read();

    Solve();

    Write();

    return 0;
}