Cod sursa(job #2043356)

Utilizator SebiSebiPirtoaca George Sebastian SebiSebi Data 19 octombrie 2017 21:57:07
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string.h>
using namespace std;

#define NMAX 10001

vector <int> v[NMAX];
int st[NMAX], dr[NMAX], viz[NMAX];

int cupleaza(int nod) {
    viz[nod] = 1;
    for (vector <int> :: iterator it = v[nod].begin(); it != v[nod].end(); it++) {
        if (dr[*it] == 0) {
            st[nod] = *it;
            dr[*it] = nod;
            return 1;
        }
        else if (viz[dr[*it]] == 0) {
            if (cupleaza(dr[*it])) {
                st[nod] = *it;
                dr[*it] = nod;
                return 1;
            }
        }
    }
    return 0;
}

int hopcroft_karp(int n) {
    int cuplaj = 0, ok = 1;
    while (ok) {
        memset(viz, 0, sizeof(viz));
        ok = 0;
        for (int i = 1; i <= n; i++)
            if (st[i] == 0 && viz[i] == 0)
                ok = ok | cupleaza(i);
    }
    for (int i = 1; i <= n; i++)
        if (st[i])
            cuplaj++;
    return cuplaj;
}

int main()
{
    int n, m, e, i, x, y;
    ifstream f("cuplaj.in");
    ofstream g("cuplaj.out");
    f >> n >> m >> e;
    for (i = 1; i <= e; i++) {
        f >> x >> y;
        v[x].push_back(y);
    }
    f.close();
    g << hopcroft_karp(n) << '\n';
    for (i = 1; i <= n; i++)
        if (st[i]) {
            g << i << " " << st[i] << '\n';
        }
    g.close();
    return 0;
}