Cod sursa(job #1391321)

Utilizator IonSebastianIon Sebastian IonSebastian Data 17 martie 2015 20:29:19
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <cstdio>
#include <cstring>
using namespace std;

const int MAX_N = 10000, MAX_M = 10000;

FILE *in, *out;

int lst[MAX_N+1], urm[MAX_N*MAX_M+1], vf[MAX_N*MAX_M+1];
int nrg;

void add(int x, int y)
{
    nrg++;
    urm[nrg] = lst[x];
    vf[nrg] = y;
    lst[x] = nrg;
}

int left[MAX_N+1], right[MAX_M+1];
bool u[MAX_N+1];

bool makepair(int nod)
{
    if(u[nod] == true) return false;
    u[nod] = true;

    int p = lst[nod];
    while(p != 0)
    {
        if(right[vf[p]] == 0)
        {
            left[nod] = vf[p];
            right[vf[p]] = nod;
            return true;
        }
        p = urm[p];
    }
    p = lst[nod];
    while(p != 0)
    {
        if(makepair(right[vf[p]]))
        {
            left[nod] = vf[p];
            right[vf[p]] = nod;
            return true;
        }
        p = urm[p];
    }
    return false;
}

int main()
{
    in = fopen("cuplaj.in", "r");
    out = fopen("cuplaj.out", "w");

    int n, m, e;
    int x, y;
    fscanf(in, "%d%d%d", &n, &m, &e);
    for(int i = 0; i < e; i++)
    {
        fscanf(in, "%d%d", &x, &y);
        add(x,y);
    }
    bool nostop = true;
    while(nostop)
    {
        nostop = false;
        memset(u, false, sizeof(u));
        for(int i = 1; i <= n; i++)
            if(left[i] == 0)
                nostop |= makepair(i);
    }
    int cup = 0;
    for(int i = 1; i <= n; i++)
        cup += (left[i] != 0);
    fprintf(out, "%d\n", cup);
    for(int i = 1; i <= n; i++)
        if(left[i] != 0)
            fprintf(out, "%d %d\n", i, left[i]);
    fclose(in);
    fclose(out);
    return 0;
}