Cod sursa(job #3271793)

Utilizator pascarualexPascaru Alexandru pascarualex Data 27 ianuarie 2025 12:58:14
Problema Cuplaj maxim in graf bipartit Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.18 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m, ed;
int S, T;
int capacity[10002][20002], flux[10002][20002];
vector<int> adj[20002];

int bfs(int s, int t) {
    vector<int> parent(20002, -1);
    parent[s] = s;
    queue<int> q;
    q.push(s);

    while (!q.empty()) {
        int u = q.front();
        q.pop();
        for (int v : adj[u]) {
            if (parent[v] == -1 && capacity[u][v] - flux[u][v] > 0) {
                parent[v] = u;
                if (v == t) {
                    // Reconstruct path
                    int flow = INT_MAX;
                    int cur = t;
                    while (cur != s) {
                        int p = parent[cur];
                        flow = min(flow, capacity[p][cur] - flux[p][cur]);
                        cur = p;
                    }
                    // Update flux
                    cur = t;
                    while (cur != s) {
                        int p = parent[cur];
                        flux[p][cur] += flow;
                        flux[cur][p] -= flow;
                        cur = p;
                    }
                    return flow;
                }
                q.push(v);
            }
        }
    }
    return 0;
}

int main(){
    fin >> n >> m >> ed;

    S = 0;
    T = n + m + 1;

    for(int i = 1; i <= n; i++){
        adj[S].push_back(i);
        adj[i].push_back(S);
        capacity[S][i] = 1;
    }


    for(int j = 1; j <= m; j++){
        adj[n+j].push_back(T);
        adj[T].push_back(n+j);
        capacity[n+j][T] = 1;
    }


    for(int e = 0; e < ed; e++){
        int i, j;
        fin >> i >> j;
        adj[i].push_back(n+j);
        adj[n+j].push_back(i);
        capacity[i][n+j] = 1;
    }

    int maxFlow = 0, flow;
    while((flow = bfs(S, T)) > 0){
        maxFlow += flow;
    }

    fout << maxFlow << "\n";

    for(int i = 1; i <= n; i++){
        for(int v : adj[i]){
            if(v >= n+1 && v <= n+m && flux[i][v] > 0){
                fout << i << " " << (v - n) << "\n";
            }
        }
    }

    return 0;
}