Cod sursa(job #2049268)

Utilizator retrogradLucian Bicsi retrograd Data 26 octombrie 2017 23:48:18
Problema Cuplaj maxim in graf bipartit Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <bits/stdc++.h>

using namespace std;

struct EZFlow {
    vector<vector<int>> G;
    vector<bool> Vis;

    int s, t;
    EZFlow(int n) : G(n), Vis(n) {}
      
    bool dfs(int node) {
        if (node == t) return true;
        if (Vis[node]) return false;
        Vis[node] = true;

        for (auto it = G[node].begin(); it != G[node].end(); ++it) {
            if (!Vis[*it] && dfs(*it)) {
                G[*it].push_back(node);
                swap(*it, G[node].back());
                G[node].pop_back();
                return true;
            }
        }
        return false;
    }

    void AddEdge(int a, int b) { G[a].push_back(b); }
    int ComputeFlow(int s, int t) {
        this->s = s; this->t = t;
        int ans = 0;
        while (dfs(s)) { ++ans; fill(Vis.begin(), Vis.end(), false); }
        return ans;
    }
};

int main() {
    freopen("cuplaj.in", "r", stdin);
    freopen("cuplaj.out", "w", stdout);
    ios_base::sync_with_stdio(false);
 
    int n, m, e; cin >> n >> m >> e;
    EZFlow flow(n + m + 2);
    int s = n + m, d = n + m + 1;
     
    while (e--) {
        int a, b; cin >> a >> b;
        flow.AddEdge(a - 1, b + n - 1);
    }
 
    for (int i = 0; i < n; ++i) flow.AddEdge(s, i);
    for (int i = 0; i < m; ++i) flow.AddEdge(i + n, d);
 
    int maxFlow = flow.ComputeFlow(s, d);
    cout << maxFlow << endl;

    for (int i = 0; i < m; ++i) {
        for (auto vec : flow.G[i + n])
            if (vec < n) {
                cout << vec + 1 << " " << i + 1 << '\n';
            }
    }
    return 0;
}