Cod sursa(job #2695789)

Utilizator AlexnolifeAlexandru Ica Alexnolife Data 14 ianuarie 2021 15:21:39
Problema Cuplaj maxim in graf bipartit Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <algorithm>
#include <array>
#include <fstream>
#include <limits>
#include <vector>

constexpr auto max_num_nodes = 10'000;

std::array<std::vector<int>, max_num_nodes> g_graph;
std::array<bool, max_num_nodes> g_visited;
std::array<int, max_num_nodes> g_tied_to;

auto dfs(int const start) noexcept -> bool
{
    for(auto const neighbor : g_graph[start]) {
        if(!g_visited[neighbor]) {
            g_visited[neighbor] = true;

            if(g_tied_to[neighbor] < 0 || dfs(g_tied_to[neighbor])) {
                g_tied_to[neighbor] = start;
                return true;
            }
        }
    }

    return false;
}

auto main() noexcept -> int
{
    std::ifstream f{ "cuplaj.in" };
    std::ofstream g{ "cuplaj.out" };

    int n = 0;
    int m = 0;
    int num_edges = 0;

    f >> n >> m >> num_edges;

    for(int i = 0; i < num_edges; ++i) {
        int from = 0;
        int to = 0;

        f >> from >> to;
        g_graph[to - 1].push_back(from - 1);
    }

    g_tied_to.fill(-1);

    int max_match = 0;

    for(int right = 0; right < m; ++right) {
        g_visited.fill(false);

        if(dfs(right)) {
            ++max_match;
        }
    }

    g << max_match << std::endl;

    for(int i = 0; i < n; ++i) {
        if(g_tied_to[i] >= 0) {
            g << i + 1 << ' ' << g_tied_to[i] + 1 << std::endl;
        }
    }
}