Cod sursa(job #1687783)

Utilizator llalexandruLungu Alexandru Ioan llalexandru Data 13 aprilie 2016 08:31:23
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <vector>
#define NM 10005

using namespace std;

ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

int n, m, p;

vector <int> G[NM];
int Valid[NM], match1[NM], match2[NM];

bool Cupleaza(int x)
{
    int i, nod;
    if (Valid[x]==1)
        return 0;
    Valid[x]=1;

    int sz=G[x].size();
    for (i=0; i<sz; i++)
    {
        nod=G[x][i];
        if (match2[nod]==0)
        {
            match2[nod]=x;
            match1[x]=nod;
            return 1;
        }
    }

    for (i=0; i<sz; i++)
    {
        nod=G[x][i];
        if( Cupleaza(match2[nod]) )
        {
            match2[nod]=x;
            match1[x]=nod;
            return 1;
        }
    }
    return 0;
}

int main()
{
    int x, y, i, ok;
    fin>>n>>m>>p;
    for (i=1; i<=p; i++)
    {
        fin>>x>>y;
        G[x].push_back(y);
    }
    ok=1;
    while (ok)
    {
        ok=0;
        for (i=1; i<=n; i++)
            Valid[i]=0;
        for (i=1; i<=n; i++)
            if (match1[i]==0)
            {
                ok+=Cupleaza(i);
            }
    }

    int sol=0;
    for (i=1; i<=n; i++)
        if(match1[i]!=0)
            sol++;
    fout<<sol<<'\n';
    for (i=1; i<=n; i++)
        if(match1[i]!=0)
        {
            fout<<i<<" "<<match1[i]<<'\n';
        }

    return 0;
}