Cod sursa(job #1479774)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 1 septembrie 2015 11:44:41
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <bits/stdc++.h>

using namespace std;

const int Nmax = 10010;

int n , m , e , i , x , y;
int cuplatSt[Nmax] , cuplatDr[Nmax];
vector < int > g[Nmax];
vector < pair < int , int > > ans;

bool ap[Nmax];

bool cupleaza(int node)
{
    ap[node] = 1;
    for (auto it : g[node])
        if (!cuplatDr[it])
        {
            cuplatSt[node] = it; cuplatDr[it] = node;
            return 1;
        }

    for (auto it : g[node])
        if (!ap[cuplatDr[it]] && cupleaza(cuplatDr[it]))
        {
            cuplatSt[node] = it; cuplatDr[it] = node;
            return 1;
        }

    return 0;
}

void cuplaj()
{
    int i; bool ok = 1;
    while (ok)
    {
        ok = false; for (i = 1; i <= n; ++i) ap[i] = 0;
        for (i = 1; i <= n; ++i)
        {
            if (cuplatSt[i] || ap[i]) continue;
            ok |= cupleaza(i);
        }
    }

    for (i = 1; i <= n; ++i)
        if (cuplatSt[i]) ans.push_back({i , cuplatSt[i]});
}

int main()
{
    freopen("cuplaj.in","r",stdin);
    freopen("cuplaj.out","w",stdout);

    scanf("%d %d %d", &n, &m, &e);

    for (i = 1; i <= e; ++i)
    {
        scanf("%d %d", &x, &y);
        g[x].push_back(y);
    }

    cuplaj();

    printf("%d\n", ans.size());
    for (auto it : ans)
        printf("%d %d\n", it.first , it.second);

    return 0;
}