Cod sursa(job #565670)

Utilizator dacyanMujdar Dacian dacyan Data 28 martie 2011 09:25:03
Problema Cuplaj maxim in graf bipartit Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <vector>
#define DIM 10001
using namespace std;

int n, m, k;
int cuplaj;
vector<int> G[DIM];

int L[DIM], R[DIM];
bool exista_cuplaj;
int s[DIM]; // vizitat

void Read();
bool Cupleaza(int x);
void Write();

int main()
{
    Read();
    do
    {
        exista_cuplaj = false;
        memset(s, false, sizeof(s));
        for (int i = 1; i <= n; ++i)
            if (!L[i] && Cupleaza(i))
            {
                cuplaj++;
                exista_cuplaj = true;
            }
    } while(exista_cuplaj);
    Write();
    return 0;
}


void Read()
{
    ifstream fin("cuplaj.in");
    fin >> n >> m >> k;
    int x, y;
    for (int i = 1; i <= k; ++i)
    {
        fin >> x >> y;
        G[x].push_back(y); // exista arc de la x (prima partitie) la y (a doua partitie)
    }
    fin.close();
}

bool Cupleaza(int nod)
{
    if (s[nod]) return false;
    s[nod] = true;
    for (vector<int>::iterator it = G[nod].begin(); it != G[nod].end(); ++it)
        if (!R[*it] || Cupleaza(*it) ) //daca nu e cuplat sau e cuplat dar gasim mai departe traseu terminat in nod liber
        {
             L[nod] = *it;
             R[*it] = nod;
             return true;
        }
    return false;
}

void Write()
{
    ofstream fout("cuplaj.out");
    fout << cuplaj << '\n';
    for (int i = 1; i <= n; ++i)
        if (L[i])
            fout << i << ' ' << L[i] << '\n';
    fout.close();
}