Cod sursa(job #2409693)

Utilizator MihaelaCismaruMihaela Cismaru MihaelaCismaru Data 19 aprilie 2019 12:44:54
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include<fstream>
#include<vector>
using namespace std;
ifstream in ("cuplaj.in");
ofstream out ("cuplaj.out");
int n,m,x,y,k,ok,cnt;
int a[10005],b[10005],hz[10005];
vector<int> v[10005];
bool cuplaj (int nod) {
    if (hz[nod] == 1) {
        return false;
    }
    hz[nod] = 1;
    for (int i = 0; i < v[nod].size(); i ++) {
        if (b[v[nod][i]] == 0) {
            b[v[nod][i]] = nod;
            a[nod] = v[nod][i];
            return 1;
        }
    }
    for (int i = 0; i < v[nod].size(); i ++) {
        if (cuplaj(b[v[nod][i]])) {
            b[v[nod][i]] = nod;
            a[nod] = v[nod][i];
            return 1;
        }
    }
    return 0;
}
int main (void) {
    in >> n >> m >> k;
    for (int i = 1; i <= k; i ++) {
        in >> x >> y;
        v[x].push_back (y);
    }

    for (int i = 1; i <= n; i ++) {
        a[i] = 0;
    }
    for (int i = 1; i <= m; i ++) {
        b[i] = 0;
    }

    ok = true;
    while (ok) {
        for (int i = 1; i <= n; i ++) {
            hz[i] = 0;
        }
        ok = false;
        for (int i = 1; i <= n; i ++) {
            if (a[i] == 0 && cuplaj(i)) {
                ok = true;
            }
        }
    }
    for (int i = 1; i <= n; i ++) {
        if (a[i] != 0) {
            cnt ++;
        }
    }
    out << cnt <<"\n";
    for (int i = 1; i <= n; i ++) {
        if (a[i] != 0) {
            out << i <<" "<< a[i] <<"\n";
        }
    }
    return 0;
}