Cod sursa(job #2696640)

Utilizator dianapingu1Diana Vasiliu dianapingu1 Data 16 ianuarie 2021 11:25:59
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <vector>

using namespace std;

const int NMAX = 100005;

int n,m,e;
vector<int> graph[NMAX];
vector<bool> viz;
vector<int> stanga, dreapta;

bool cuplaj(int nod) {
    if (viz[nod]) {
        return false;
    }

    viz[nod] = true;

    for (auto &vec : graph[nod]) {
        if (!dreapta[vec]) {
            stanga[nod] = vec;
            dreapta[vec] = nod;
            return true;
        }
    }

    for (auto &vec : graph[nod]) {
        if (cuplaj(dreapta[vec])) {
            stanga[nod] = vec;
            dreapta[vec] = nod;
            return true;
        }
    }

    return false;
}

int main() {

    ifstream fin("cuplaj.in");
    ofstream fout("cuplaj.out");

    fin >> n >> m >> e;
    for (int i = 1; i <= e; i++) {
        int x,y;
        fin >> x >> y;
        graph[x].push_back(y);
    }
    bool ok = true;
    viz.resize(n + m);
    int ans = 0;
    stanga.resize(n + 1);
    dreapta.resize(m + 1);

    while (ok) {
        ok = false;
        fill(viz.begin(), viz.end(), false);
        for (int i = 1; i <= n; i++) {
            if (!stanga[i] && cuplaj(i)) {
                ans++;
                ok = true;
            }
        }
    }

    fout << ans << "\n";

    for (int i = 1; i <= n; i++) {
        if (stanga[i]) {
            fout << i << " " << stanga[i] << "\n";
        }
    }

    fin.close();
    fout.close();
    return 0;
}