Cod sursa(job #2655845)

Utilizator pregoliStana Andrei pregoli Data 5 octombrie 2020 19:04:36
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <bits/stdc++.h>
using namespace std;
#define STOP fout.close(); exit(EXIT_SUCCESS);
ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");
///***********************
const int NMAX = 1e4 + 3;
vector<int> graph[NMAX];
int n, m, e, ans;
bool vis[NMAX];
int lpOf[NMAX], rpOf[NMAX];//left/right pair of i

void read() {
    fin >> n >> m >> e;
    for (int a, b, i = 0; i < e; i++) {
        fin >> a >> b;
        graph[a].push_back(b);
    }
}

inline bool match(int node) {
    if (vis[node])
        return false;
    vis[node] = true;
    for (int it : graph[node])
        if (!lpOf[it]) {
            rpOf[node] = it;
            lpOf[it] = node;
            return true;
        }
    for (int it : graph[node])
        if (match(lpOf[it])) {
            rpOf[node] = it;
            lpOf[it] = node;
            return true;
        }
    return false;
}

void solve() {
    bool ready = false;
    while (!ready) {
        ready = true;
        fill(vis + 1, vis + n + 1, false);
        for (int i = 1; i <= n; i++)
            if (!rpOf[i] && match(i)) {
                ans++;
                ready = false;
            }
    }
}

void display() {
    fout << ans << '\n';
    for (int i = 1; i <= n; i++)
        if (rpOf[i])
            fout << i << ' ' << rpOf[i] << '\n';
}

int main() {
    read();
    solve();
    display();
    STOP
}