Cod sursa(job #2409348)

Utilizator alexge50alexX AleX alexge50 Data 18 aprilie 2019 22:11:05
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <vector>
#include <array>
#include <cstring>

const int MAX_N = 10000;

using Graph = std::array<std::vector<int>, MAX_N + 1>;
Graph graph;
std::array<int, MAX_N + 1> left, right;
std::array<bool, MAX_N + 1> saturated;

bool repair(int root)
{
    if(saturated[root])
        return false;
    saturated[root] = true;

    for(const auto x: graph[root])
    {
        if(!right[x])
        {
            left[root] = x;
            right[x] = root;

            return true;
        }
    }

    for(const auto x: graph[root])
    {
        if(repair(right[x]))
        {
            left[root] = x;
            right[x] = root;

            return true;
        }
    }


    return false;
}

int main()
{
    std::ios_base::sync_with_stdio(false);
    std::ifstream fin("cuplaj.in");
    std::ofstream fout("cuplaj.out");

    int n, m, e;
    int coupling;

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

        graph[x].push_back(y);
    }

    bool ok = true;
    coupling = 0;
    while(ok)
    {
        ok = false;
        std::memset(&saturated[0], 0, sizeof(saturated));
        for(int i = 1; i <= n; i++)
            if(!left[i])
            {
                int x = repair(i);
                ok = ok || x;
                coupling += x;
            }
    }

    fout << coupling << '\n';
    for(int i = 1; i <= n; i++)
    {
        if(left[i])
            fout << i << ' ' << left[i] << '\n';
    }

    return 0;
}