Cod sursa(job #2130708)

Utilizator Laura_CorneiLaura Maria Cornei Laura_Cornei Data 13 februarie 2018 20:50:59
Problema Cuplaj maxim in graf bipartit Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>
#include <string.h>
#include <stdlib.h>
#include <vector>
#define nmax 10005
using namespace std;
fstream f1("cuplaj.in", ios::in);
fstream f2("cuplaj.out", ios::out);
int l[nmax], r[nmax], nrl, nrr, m, viz[nmax], match[nmax*2], nrmatches;
vector <int> v[nmax];
///match[j]=i, unde j nod din R, iar i nod din L
void citire()
{
    int i, x, y, var1=0, var2=0;
    f1>>nrl>>nrr>>m;
    for(i=1; i<=m; i++)
    {
        f1>>x>>y;
        y+=nrl;
        v[x].push_back(y);
        v[y].push_back(x);
        if(!viz[x])
        {
            viz[x]=1;
            var1++;
            l[var1]=x;
        }
        if(!viz[y])
        {
            viz[y]=1;
            var2++;
            r[var2]=y;
        }
    }
}
int Cauta_pereche(int i)
{
    for(auto it=v[i].begin(); it!=v[i].end(); ++it)
        if(!viz[*it]) ///daca e vizitat te-ai dus deja pe o infundatura
    {
        ///vrei sa unesti i cu *it=j, daca j era unit cu k, vezi cu cine il mai poti uni pe k in afara de j
        viz[*it]=1;///ca sa nu ii atribui din nou lui k vecinul j
        if((match[*it]==0)||(Cauta_pereche(match[*it])))
        {
            match[*it]=i;
            return 1;
        }
    }
    return 0;
}
void solutie()
{
    ///incercam sa gasim pereche pentru fiecare nod din multimea l
    int i;
    for(i=1; i<=nrl; i++)
    {
        memset(viz, 0, sizeof(viz));
        if(Cauta_pereche(l[i])) nrmatches++;
    }
}
void afisare()
{
    int i;
    f2<<nrmatches<<"\n";
    for(i=1; i<=nrmatches; i++)
        f2<<match[r[i]]<<' '<<r[i]-nrl<<"\n";
}
int main()
{
    citire();
    solutie();
    afisare();
    return 0;
}