Cod sursa(job #3152993)

Utilizator Chris_BlackBlaga Cristian Chris_Black Data 27 septembrie 2023 16:04:45
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <bits/stdc++.h>

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

const int N = 10009;

int n, m, e, u, v, L[N], R[N];
vector<vector<int>> G;
bitset<N> viz;

bool DoMatch(int x)
{
    if(viz[x])return false;
    viz[x] = true;

    for(auto y : G[x])
        if(!R[y])
        {
            R[y] = x;
            L[x] = y;
            return true;
        }

    for(auto y : G[x])
        if(DoMatch(R[y]))
        {
            R[y] = x;
            L[x] = y;
            return true;
        }


    return false;
}

void Match()
{
    bool found_match = true;
    while(found_match)
    {
        found_match = false;

        viz.reset();
        for(int i = 1; i <= n; ++i)
            if(!L[i]) found_match |= DoMatch(i);
    }
}

int main()
{
    fin >> n >> m >> e;
    G = vector<vector<int>>(n + 1);
    for(int i = 1; i <= e; ++i)
    {
        fin >> u >> v;
        G[u].push_back(v);
    }

    Match();

    int ans = 0;
    for(int i = 1; i <= n; ++i)
        if(L[i])ans ++;
    fout << ans <<'\n';
    for(int i = 1; i <= n; ++i)
        if(L[i])fout << i << ' ' << L[i] << '\n';
    return 0;
}