Cod sursa(job #3336948)

Utilizator petric_mariaPetric Maria petric_maria Data 26 ianuarie 2026 19:43:58
Problema Cuplaj maxim in graf bipartit Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("cuplaj.in");
ofstream g("cuplaj.out");

const int inf = 1e9 + 7;
int n, m, e, x, y, c[10005][10005], flow[10005][10005], d[20005];
vector <int> v[20005];
int ans = 0;

bool bfs (int s, int t) {
    for (int i=1; i<=n+m+1; ++i)
        d[i] = INT_MAX;
    d[s] = 0;
    queue <int> q;
    q.push(s);

    while (!q.empty()) {
        int k = q.front();
        q.pop();
        for (auto x: v[k])
            if (c[k][x] > flow[k][x] && d[x] > d[k] + 1) {
                d[x] = d[k] + 1;
                q.push (x);
            }
    }
    return d[t] != INT_MAX;
}
int maxFlow (int node, int destination, int max_flow) {
    if (max_flow == 0)
        return 0;
    if (node == destination)
        return max_flow;
    int total_flow = 0;

    for (auto x: v[node])
        if (d[x] == d[node] + 1) {
            int new_max_flow = min (max_flow - total_flow, c[node][x] - flow[node][x]);
            int new_flow = maxFlow (x, destination, new_max_flow);

            flow[node][x] += new_flow;
            flow[x][node] -= new_flow;
            total_flow += new_flow;
        }
    return total_flow;
}

int main()
{
    f >> n >> m >> e;
    int s = 0, t = n + m + 1;

    for (int i=1; i<=e; ++i) {
        f >> x >> y;
        v[x].push_back (y + n);
        v[y+n].push_back (x);
        c[x][y+n] = 1;
    }

    for (int i=1; i<=n; ++i) {
        v[s].push_back (i);
        v[i].push_back (s);
        c[s][i] = 1;
    }
    for (int i=1; i<=m; ++i) {
        v[i+n].push_back (t);
        v[t].push_back (i+n);
        c[i+n][t] = 1;
    }

    while (bfs(s, t))
        ans += maxFlow (s, t, INT_MAX);

    g << ans << '\n';

    for (int i=1; i<=n; ++i)
        for (auto x: v[i])
            if (x > n && x <= n + m && flow[i][x] == 1)
                g << i << ' ' << x - n << '\n';

    return 0;
}