Cod sursa(job #3181535)

Utilizator octavian202Caracioni Octavian Luca octavian202 Data 7 decembrie 2023 09:44:58
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

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

const int NMAX = 20003;
int n, m, e, l[NMAX], r[NMAX];
vector<int> g[NMAX];
bool vis[NMAX];

bool pair_up(int nod) { // nod e din stanga
    if (vis[nod])
        return false;
    vis[nod] = true;

    for (auto v : g[nod]) { // incerc sa cuplez
        if (r[v] == 0) {
            l[nod] = v;
            r[v] = nod;
            return true;
        }
    }

    for (auto v : g[nod]) { // incerc sa schimb un cuplaj ca sa pot cupla nod
        if (pair_up(r[v])) {
            l[nod] = v;
            r[v] = nod;
            return true;
        }
    }

    return false;
}

void cuplaj_maxim() {
    for (bool ok = false; !ok;) {
        ok = true;
        memset(vis, 0, sizeof(vis));
        for (int i = 1; i <= n; i++) {
            if (l[i] == 0 && pair_up(i)) {
                ok = false;
            }
        }
    }
}

int main() {

    fin >> n >> m >> e;
    for (int i = 1; i <= e; i++) {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y + n);
        g[y + n].push_back(x);
    }

    cuplaj_maxim();

    for (int i = 1; i <= n; i++) {
        if (l[i] != 0)
            fout << i << ' ' << l[i] - n << '\n';
    }


    return 0;
}