Cod sursa(job #2962687)

Utilizator witekIani Ispas witek Data 8 ianuarie 2023 22:57:50
Problema Cuplaj maxim in graf bipartit Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 kb
#include <bits/stdc++.h>

using namespace std;
const int NMAX = 1000;

int cost[NMAX + 5][NMAX + 5];
bool viz[NMAX + 5];

int BFS(int node, int n, int &ans, vector<vector<int>> &G, int maxFlow) {
    if(node == n) {
        ans += maxFlow;
        return maxFlow;
    }

    viz[node] = 1;

    int totalFlow = 0;

    for(auto &adj : G[node]) {
        if(maxFlow == 0)
            return totalFlow;

        if(viz[adj] || !cost[node][adj])
            continue;

        int currFlow = BFS(adj, n, ans, G, min(maxFlow, cost[node][adj]));
        cost[node][adj] -= currFlow;
        cost[adj][node] += currFlow;
        totalFlow += currFlow;
        maxFlow = maxFlow - currFlow;
    }

    return totalFlow;
}

void DFS(int node, vector<vector<int>> &G) {
    viz[node] = 1;

    for(auto &adj : G[node]) {
        cout << node << " " << adj << " " << cost[node][adj] << " " << viz[adj] << '\n';
        if(cost[node][adj] && !viz[adj])
            DFS(adj, G);
    }
}

int main()
{
    //ios::sync_with_stdio(false);
    ifstream fin("cuplaj.in");
    ofstream fout("cuplaj.out");
    fin.tie(0);
    fout.tie(0);

    int n, m, e;

    fin >> n >> m >> e;

    vector<vector<int>> G(n + m + 2, vector<int>());

    for(int i = 1; i <= e; i++) {
        int a, b;

        fin >> a >> b;

        b = n + b;
        G[a].push_back(b);
        G[b].push_back(a);

        cost[a][b] = 1;
    }

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

        cost[0][i] = 1;
    }

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

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

    int ans = 0;

    while(BFS(0, n + m + 1, ans, G, 1e9)) {
        for(int i = 0; i <= n + m; i++)
            viz[i] = 0;
    }

    fout << ans << '\n';

    for(int i = 1; i <= n; i++)
        for(auto &adj: G[i])
            if(adj > n && !cost[i][adj])
                fout << i << " " << adj - n << '\n';

    fin.close();
    fout.close();

    return 0;
}