Cod sursa(job #2227011)

Utilizator ContDeRacistAliniateEBlat ContDeRacist Data 30 iulie 2018 21:42:44
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <fstream>
#include <vector>
#include <cstring>

using namespace std;

ifstream cin("cuplaj.in");
ofstream cout("cuplaj.out");

const int N = 1e4 + 5;

vector < int > adia[N];
vector < pair < int, int > > ans;
int st[N], dr[N];

bool viz[N];

int n, m;

void adauga(int x, int y) {
    adia[x].push_back(y);
}

bool cuplaj(int nod) {
    if (viz[nod]) {
        return false;
    }
    viz[nod] = 1;
    for (auto i : adia[nod]) {
        if (!st[i]) {
            st[i] = nod;
            dr[nod] = i;
            return true;
        }
        if (cuplaj(st[i])) {
            st[i] = nod;
            dr[nod] = i;
            return true;
        }
    }
    return false;
}

void mk_cuplaj() {
    bool act(1);
    while (act) {
        memset(viz, false, N);
        act = 0;
        for (int i = 1; i <= n; ++i) {
            if (dr[i] == 0 && !viz[i] && cuplaj(i)) {
                act = 1;
            }
        }
    }
}

int main()
{
    int e, a, b;
    cin >> n >> m >> e;
    for (int i = 0; i < e; ++i) {
        cin >> a >> b;
        adauga(a, b);
    }
    mk_cuplaj();
    for (int i = 1; i <= n; ++i) {
        if (dr[i]) {
            ans.push_back({i, dr[i]});
        }
    }
    cout << ans.size() << '\n';
    for (int i = 0; i < ans.size(); ++i) {
        cout << ans[i].first << ' ' << ans[i].second << '\n';
    }
    return 0;
}