Cod sursa(job #2962373)

Utilizator AntoniaPopoviciAntonia-Adelina Popovici AntoniaPopovici Data 8 ianuarie 2023 14:33:30
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1e4 + 5;
const int INF = 1e9;


ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");
int n, m, e;
vector<int> adj[MAXN];
int res[MAXN][MAXN];
int f[MAXN];
bool vis[MAXN];

int bfs(int s, int t) {
    queue<int> q;
    q.push(s);
    memset(vis, false, sizeof(vis));
    f[s] = INF;
    vis[s] = true;
    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int v : adj[u]) {
            if (!vis[v] && res[u][v] > 0) {
                vis[v] = true;
                f[v] = min(f[u], res[u][v]);
                if (v == t) {
                    return f[t];
                }
                q.push(v);
            }
        }
    }
    return 0;
}

int max_flow(int s, int t) {
    int flow = 0;
    while (int df = bfs(s, t)) {
        flow += df;
        for (int u = t; u != s; u = f[u]) {
            int v = f[u];
            res[v][u] -= df;
            res[u][v] += df;
        }
    }
    return flow;
}

int main() {
    fin >> n >> m >> e;
    for (int i = 1; i <= e; i++) {
        int u, v;
        fin >> u >> v;
        adj[u].push_back(v + n);
        adj[v + n].push_back(u);
        res[u][v + n] = 1;
    }

    int s = 0, t = 2 * n + 1;
    for (int i = 1; i <= n; i++) {
        adj[s].push_back(i);
        adj[i].push_back(s);
        res[s][i] = 1;
    }
    for (int i = n + 1; i <= n + m; i++) {
        adj[i].push_back(t);
        adj[t].push_back(i);
        res[i][t] = 1;
    }

    int max_coupling = max_flow(s, t);
    fout << max_coupling << endl;
    for (int u = 1; u <= n; u++) {
        for (int v : adj[u]) {
            if (res[v][u] == 1) {
                fout << u << " " << v - n << endl;
            }
        }
    }

    return 0;
}