Cod sursa(job #3336802)

Utilizator petru-robuRobu Petru petru-robu Data 25 ianuarie 2026 22:15:39
Problema Cuplaj maxim in graf bipartit Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.16 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m, e, maxflow;
vector<vector<int>> adj_list, cap, flow;
vector<int> parent, visited;

void read()
{
    fin >> n >> m >> e;

    adj_list.assign(n + m + 2, {});
    cap.assign(n + m + 2, vector<int>(n + m + 2, 0));
    flow.assign(n + m + 2, vector<int>(n + m + 2, 0));

    for (int i = 0; i < e; i++)
    {
        int x, y;
        fin >> x >> y;

        adj_list[x].push_back(n + y);
        adj_list[n + y].push_back(x);

        cap[x][n + y] = 1;
    }

    for (int i = 1; i <= n; i++)
    {
        adj_list[0].push_back(i);
        adj_list[i].push_back(0);

        cap[0][i] = 1;
    }

    for (int i = n + 1; i <= m + n; i++)
    {
        adj_list[m + n + 1].push_back(i);
        adj_list[i].push_back(m + n + 1);

        cap[i][m + n + 1] = 1;
    }
}

bool find_path()
{
    parent.assign(m + n + 2, -1);
    visited.assign(m + n + 2, 0);
    queue<int> Q;

    Q.push(0);
    visited[0] = 1;

    while (!Q.empty())
    {
        int x = Q.front();
        Q.pop();

        for (auto &next : adj_list[x])
        {
            if (!visited[next] && cap[x][next] > flow[x][next])
            {
                parent[next] = x;
                Q.push(next);

                visited[next] = 1;

                if (next == m + n + 1)
                    return true;
            }
        }
    }
    return false;
}

void edmonds()
{
    while (find_path())
    {
        int bottleneck = INT_MAX;
        for (int v = m + n + 1; v != 0; v = parent[v])
        {
            bottleneck = min(bottleneck, cap[parent[v]][v] - flow[parent[v]][v]);
        }

        for (int v = m + n + 1; v != 0; v = parent[v])
        {
            flow[parent[v]][v] += bottleneck;
            flow[v][parent[v]] -= bottleneck;
        }

        maxflow += bottleneck;
    }

    fout << maxflow << '\n';
}

void print_cuplaj()
{
    for (int u = 1; u <= n; u++)
        for (int v : adj_list[u])
            if (v >= n + 1 && v <= n + m && flow[u][v] == 1)
                fout << u << " " << (v - n) << "\n";
}

int main()
{
    read();
    edmonds();
    print_cuplaj();
    return 0;
}