Cod sursa(job #1943022)

Utilizator razvan242Zoltan Razvan-Daniel razvan242 Data 28 martie 2017 12:23:13
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <bitset>

using namespace std;

const int NMAX = 1e4 + 1;

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

int lNodes, rNodes, m;
vector<int> L, R;
vector<vector<int> > v;
bitset<NMAX> viz;

inline void read() {
    fin >> lNodes >> rNodes >> m;
    L = vector<int>(lNodes + 1);
    R = vector<int>(rNodes + 1);
    v = vector<vector<int> >(lNodes + 1);
    int x, y;
    for (int i = 1; i <= m; ++i) {
        fin >> x >> y;
        v[x].push_back(y);
    }
}

int getAlternatingChain(int node) {
    if (viz[node])
        return 0;
    viz[node] = 1;
    for (const int& other: v[node]) {
        if (!R[other] || getAlternatingChain(R[other])) {
            L[node] = other;
            R[other] = node;
            return 1;
        }
    }
    return 0;
}

inline void getCover() {
    int hadChanges = 1;
    while (hadChanges) {
        hadChanges = 0;
        viz.reset();
        for (int i = 1; i <= lNodes; ++i) {
            if (!L[i])
                hadChanges |= getAlternatingChain(i);
        }
    }

    vector<pair<int, int> > ans;
    for (int i = 1; i <= lNodes; ++i)
        if (L[i])
            ans.push_back({i, L[i]});

    fout << ans.size() << '\n';
    for (auto i: ans)
        fout << i.first << ' ' << i.second << '\n';
}

int main()
{
    read();
    getCover();

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