Cod sursa(job #2803288)

Utilizator smoc_georgemarianSmoc George-Marian smoc_georgemarian Data 19 noiembrie 2021 19:06:49
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.19 kb
#include <bits/stdc++.h>
#define int int64_t
#define double long double
using namespace std;
ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");

class Cuplaj
{
    vector<int> st;
    vector<int> dr;
    vector<int> uz;
    vector<pair<int, int>> result;
    int nr = 0;
    const vector<vector<int>> &g;

public:
    Cuplaj(const vector<vector<int>> &g_tmp, int st_size, int dr_size) : g(g_tmp)
    {
        st.resize(st_size + 1);
        uz.resize(st_size + 1);
        dr.resize(dr_size + 1);
    }
    void compute_cuplaj()
    {
        int i;
        bool ok = 1;
        while (ok)
        {
            ok = 0;
            fill(uz.begin(), uz.end(), 0);
            for (i = 1; i < st.size(); i++)
                if (!st[i] && !uz[i])
                    if (expand_cuplaj(i))
                        ok = 1;
        }
        fill(uz.begin(), uz.end(), 0);
        for (i = 1; i < st.size(); i++)
            if (st[i])
                nr++;

        for (i = 1; i < st.size(); i++)
            if (st[i])
                result.push_back({i, st[i]});
    }
    bool expand_cuplaj(int node)
    {
        int i, vec;
        if (uz[node])
            return 0;
        uz[node] = 1;
        for (i = 0; i < g[node].size(); i++)
        {
            vec = g[node][i];
            if (!dr[vec]) /// pun muchie
            {
                st[node] = vec; /// cuplez
                dr[vec] = node;
                return 1;
            }
        }
        for (i = 0; i < g[node].size(); i++)
        {
            vec = g[node][i];
            if (expand_cuplaj(dr[vec]))
            {
                st[node] = vec;
                dr[vec] = node;
                return 1;
            }
        }
        return 0;
    }
    void print_result()
    {
        int i;
        fout << nr << '\n';
        for (i = 0; i < result.size(); i++)
            fout << result[i].first << " " << result[i].second << '\n';
    }
};
int32_t main()
{
    int i;
    int ns, nd, m;
    fin >> ns >> nd >> m;
    vector<vector<int>> g(ns+1);
    for (i = 0; i < m; i++)
    {
        int x, y;
        fin >> x>> y;
        g[x].push_back(y);
    }
    Cuplaj c(g, ns,nd);
    c.compute_cuplaj();
    c.print_result();
    return 0;
}