Cod sursa(job #1885102)

Utilizator antanaAntonia Boca antana Data 19 februarie 2017 17:00:41
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <cstdio>
#include <vector>
#include <cstring>

#define MAXN 10001

using namespace std;

vector <int> G[MAXN];

int n, m, edges, left[MAXN], right[MAXN];
bool seen[MAXN];

bool match(int node)
{
    if(seen[node]) return 0;

    int son, i;

    seen[node] = 1;
    for(i=0; i<G[node].size(); ++i)
    {
        son = G[node][i];
        if(!right[son])
        {
            left[node] = son;
            right[son] = node;
            return 1;
        }
    }

    for(i=0; i<G[node].size(); ++i)
    {
        son = G[node][i];
        if(match(right[son]))
        {
            left[node] = son;
            right[son] = node;
            return 1;
        }
    }

    return 0;
}

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

    int f, x, y, i;

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

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

    f = 1;
    while(f)
    {
        f = 0;
        memset(seen, 0, sizeof seen);
        for(i=1; i<=n; ++i)
            if(!left[i])
                f = f | match(i);
    }

    int ans =0;
    for(i=1; i<=n; ++i)
        if(left[i])
            ans++;

    printf("%d\n", ans);

    for(i=1; i<=n; ++i)
        if(left[i])
            printf("%d %d\n", i, left[i]);
    return 0;
}