Cod sursa(job #2698641)

Utilizator LittleWhoFeraru Mihail LittleWho Data 22 ianuarie 2021 16:58:19
Problema Cuplaj maxim in graf bipartit Scor 24
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.2 kb
#include <bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
typedef signed long long ll;
typedef unsigned int uint;
typedef unsigned short ushort;
typedef unsigned char uchar;
template <typename T>
void printarray(T v[], uint n) {for(uint i = 0; i < n; i ++){cout << v[i] << " ";}cout << endl;}
template <typename T>
void printvector(vector<T> v){for (uint i = 0; i < v.size(); i ++){cout << v[i] << " ";}cout << endl;}
#define dbg(x) cout << #x " = " << x << " | ";
#define dbgnl(x) cout << #x " = " << x << endl;

const uint nmax = 10005;
const int INF = 2e9;

list<int> G[nmax];
int maxflow = 0;
int n, m, e;
bitset<nmax> visited;
int left_nodes[nmax], right_nodes[nmax];

void read() {
    cin >> n >> m >> e;
    for (int i = 0; i < e; i++) {
        int x, y;
        cin >> x >> y;
        G[x].push_back(y);
    }
}

bool pairup(int node) {
    if (visited[node]) return false;
    visited[node] = true;

    // pair-up the first node you find free (right to left)
    for (auto neighbour: G[node]) {
        if (right_nodes[neighbour] == 0) {
            left_nodes[node] = neighbour;
            right_nodes[neighbour] = node;
            return true;
        }
    }

    // pair-up the neighbours of the node
    for (auto neighbour: G[node]) {
        if (pairup(neighbour) == true) {
            left_nodes[node] = neighbour;
            right_nodes[neighbour] = node;
            return true;
        }
    }

    // couldn't pair :(
    return false;
}

void solve() {
    int retry = true;
    while (retry) {
        retry = false;
        // try to pair all free nodes on the left
        for (int i = 1; i <= n; i++) {
            if (left_nodes[i] == 0) retry = retry || pairup(i);
        }
        visited.reset();
    }

    for (int i = 1; i <= n; i++) {
        if (left_nodes[i]) maxflow++;
    }
}

void write() {
    cout << maxflow << "\n";
    for (int i = 1; i <= n; i++) {
        if (left_nodes[i] != 0) cout << i << " " << left_nodes[i] << "\n";
    }
}

int main() {
    freopen("cuplaj.in", "r", stdin);
    freopen("cuplaj.out", "w", stdout);

    read();
    solve();
    write();

    return 0;
}