Cod sursa(job #3348845)

Utilizator MMEnisEnis Mutlu MMEnis Data 24 martie 2026 14:32:11
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("cuplaj.in");
ofstream g("cuplaj.out");

vector <int> adj[100001];
int match_left[100001];
int match_right[100001];
int dist[100001];
int n, m, p;

bool bfs ()
{
    queue <int> q;
    for ( int i = 1; i <= n; i ++ )
    {
        if ( !match_left[i] )
            dist[i] = 0, q.push(i);
        else dist[i] = INT_MAX;
    }
    bool found = 0;
    while ( q.size() )
    {
        int nod = q.front(); q.pop();
        for ( auto it : adj[nod] )
        {
            if ( match_right[it] == 0 )
                found = true;
            else if ( dist[match_right[it]] == INT_MAX )
            {
                dist[match_right[it]] = dist[nod] + 1;
                q.push( match_right[it] );
            }
        }
    }
    return found;
}

bool dfs ( int nod )
{
    for ( auto it : adj[nod] )
    {
        if ( match_right[it] == 0 || ( dist[match_right[it]] == dist[nod] + 1 && dfs ( match_right[it] ) ))
        {
            match_left[nod] = it;
            match_right[it] = nod;
            return true;
        }
    }
    dist[nod] = INT_MAX;
    return false;
}

int main()
{
    f >> n >> m >> p;
    for ( int i = 1; i <= p; i ++ )
    {
        int u, v;
        f >> u >> v;
        adj[u].push_back(v);
    }
    int matches = 0;
    while ( bfs() )
        for ( int i = 1; i <= n; i ++ )
            if ( match_left[i] == 0 && dfs(i) )
                matches ++;
    g << matches << '\n';
    for ( int i = 1; i <= n; i ++ )
        if ( match_left[i] )
            g << i << " " << match_left[i] << '\n';
    return 0;
}