Cod sursa(job #1452388)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 20 iunie 2015 17:36:29
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>

using namespace std;

const int Nmax = 10010;

int n , m , edges , x , y;
int cuplat_ST[Nmax] , cuplat_DR[Nmax];

bool marked[Nmax];

vector < int > g[Nmax];
vector < pair < int , int > > ans;

bool cupleaza(int node)
{
    marked[node] = true;
    for (int i = 0; i < g[node].size(); ++i)
        if (!cuplat_DR[g[node][i]])
        {
            cuplat_ST[node] = g[node][i]; cuplat_DR[g[node][i]] = node;
            return 1;
        }

    for (int i = 0; i < g[node].size(); ++i)
        if (!marked[cuplat_DR[g[node][i]]] && cupleaza(cuplat_DR[g[node][i]]))
        {
            cuplat_ST[node] = g[node][i]; cuplat_DR[g[node][i]] = node;
            return 1;
        }

    return 0;
}

void cuplaj()
{
    bool ok = true;
    while (ok)
    {
        ok = false;
        memset(marked , false , sizeof(marked));
        for (int i = 1; i <= n; ++i)
            if (!cuplat_ST[i] && !marked[i])
                ok |= cupleaza(i);
    }

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

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

    /// cuplat_ST[i] - cu cine e cuplat nodul i din stanga
    /// cuplat_DR[i] - cu cine e cuplat nodul i din dreapta

    for (scanf("%d %d %d", &n, &m, &edges); edges; --edges)
    {
        scanf("%d %d", &x ,&y);
        g[x].push_back(y);
    }

    cuplaj();

    for (printf("%d\n", ans.size()); ans.size(); ans.pop_back())
        printf("%d %d\n", ans.back().first , ans.back().second);

    return 0;
}