Cod sursa(job #1374518)

Utilizator oprea1si2si3Oprea Sebastian oprea1si2si3 Data 5 martie 2015 09:45:49
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <fstream>
#include <vector>
#include <cstring>
using namespace std;

const int kNMax = 10005;
int sol, n1, n2, stanga[kNMax], dreapta[kNMax];
vector<int> G[kNMax];
bool used[kNMax];

void Citire() {
    ifstream in("cuplaj.in");
    int x, y, m;
    in >> n1 >> n2 >> m;
    while (m--) {
        in >> x >> y;
        G[x].push_back(y);
    }
    in.close();
}

int PairUp (int nod) {
    if (used[nod])
        return 0;
    used[nod] = 1;
    for (int i = 0; i < G[nod].size(); ++i) {
        int vecin = G[nod][i];
        if (!dreapta[vecin]) {
            stanga[nod] = vecin;
            dreapta[vecin] = nod;
            return 1;
        }
    }
    for (int i = 0; i < G[nod].size(); ++i) {
        int vecin = G[nod][i];
        if (PairUp(dreapta[vecin])) {
            stanga[nod] = vecin;
            dreapta[vecin] = nod;
            return 1;
        }
    }
    return 0;
}

void Solve() {
    int ok;
    ok = 1;
    while (ok) {
        ok = 0;
        memset(used, 0, sizeof(used));
        for (int i = 1; i <= n1; ++i)
            if (!stanga[i])
                if (PairUp(i))
                    ok = 1;
    }
    for(int i = 1; i <= n1; ++i)
        if (stanga[i])
            sol++;
}

void Afisare() {
    ofstream out("cuplaj.out");
    out << sol << '\n';
    for (int i = 1; i <= n1; ++i)
        if (stanga[i])
            out << i << ' ' << stanga[i] << '\n';
    out.close();
}

int main() {
    Citire();
    Solve();
    Afisare();
    return 0;
}