Cod sursa(job #2821157)

Utilizator francescom_481francesco martinut francescom_481 Data 22 decembrie 2021 10:48:03
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("cuplaj.in");
ofstream fout("cuplaj.out");
#define cin fin
#define cout fout

#define N 20005
#define mod 777000013
vector < vector < int > > g;
int divi, rez, sol, n, m, p, x, y, f[N], cuplu[N];

void cuplat(int x, int y)
{
    cuplu[cuplu[x]] = 0;
    cuplu[cuplu[y]] = 0;
    cuplu[x] = y;
    cuplu[y] = x;
}
int dfs(int nod)
{
    f[nod] = divi;
    for(auto t : g[nod])
    {
        if(f[t] < divi)
        {
            f[t] = divi;
            if(cuplu[t] == 0)
            {
                cuplat(nod,t);
                return 1;
            }
            else
            {
                if(dfs(cuplu[t]))
                {
                    cuplat(nod,t);
                    return 1;
                }
            }
        }
    }
    return 0;
}

int main()
{
    cin >> n >> m >> p;
    g.resize(n+m+1);
    for(int i = 1 ; i <= p ; i++)
    {
        cin >> x >> y;
        g[x].push_back(y+n);
        g[y+n].push_back(x);
    }
    rez = 1;
    while(rez)
    {
        rez = 0;
        divi++;
        for(int i = 1 ; i <= n+m ; i++)
        {
            if(f[i] < divi  &&  cuplu[i] == 0)
            {
                rez = rez|dfs(i);
            }
        }
    }
    for(int i = 1 ; i <= n ; i++)
    {
        if(cuplu[i] != 0)sol++;
    }
    cout << sol << '\n';
    for(int i = 1 ; i <= n ; i++)
    {
        if(cuplu[i] != 0)
        {
            cout << i << " " << cuplu[i]-n << '\n';
        }
    }
    return 0;
}