Cod sursa(job #1962999)

Utilizator savulescustefanSavulescu Stefan savulescustefan Data 12 aprilie 2017 10:55:50
Problema Cuplaj maxim in graf bipartit Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.08 kb
#include <cstdio>
#include <vector>
using namespace std;
vector <int> v[10004],v1[10004],s;
int n,m,e,i,x,y,nr1,nr[10004],a[10004],b[10004],k,j,h,q,z,u[10004],w;
bool ok,ok1;
void cupleaza (int x)
{
    int z,w,q,k,y;
    z=v[x].size();
    for (k=0;k<=(z-1);k++)
    {
        q=b[v[x][k]];
        if (nr[q]>0 && q!=x)
        {
            w=v[q].size();
            for (j=0;j<=(w-1);j++)
            {
                if (a[v[q][j]]==0)
                    break;
            }
            a[v[q][j]]=1;
            b[v[q][j]]=q;
            b[v[x][k]]=x;
            y=v1[v[q][j]].size();
            for (w=0;w<=(y-1);w++)
                nr[v1[v[q][j]][w]]--;
            ok=true;
            nr1++;
            return;
        }
        else if (u[q]==0)
        {
            u[q]=1;
            cupleaza(q);
            if (ok==true)
            {
                b[v[x][k]]=x;
                return;
            }
        }
    }
    return;
}
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);
        v[x].push_back(y);
        v1[y].push_back(x);
        nr[x]++;
    }
    nr1=0;
    for (i=1;i<=n;i++)
    {
        ok=false;
        k=v[i].size();
        for (j=0;j<=(k-1);j++)
        {
            if (a[v[i][j]]==0)
            {
                a[v[i][j]]=1;
                b[v[i][j]]=i;
                ok=true;
                nr1++;
                z=v1[v[i][j]].size();
                for (h=0;h<=(z-1);h++)
                    nr[v1[v[i][j]][h]]--;
                break;
            }
        }
        if (ok==false && k>=1)
            s.push_back(i);
    }
    h=s.size();
    for (i=0;i<=(h-1);i++)
    {
        ok=false;
        u[s[i]]=1;
        cupleaza(s[i]);
        for (j=1;j<=n;j++)
            u[j]=0;
    }
    printf ("%d\n", nr1);
    for (i=1;i<=m;i++)
    {
        if (b[i]!=0)
            printf ("%d %d\n", b[i], i);
    }
    return 0;
}