Cod sursa(job #3225525)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 17 aprilie 2024 19:47:51
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("cuplaj.in");
ofstream cout("cuplaj.out");
using ll = long long;
const int nmax = 1e4 + 1;
using pii = pair<int,int>;
int n , m , e , a , b;
vector <int> g[nmax];
bool viz[nmax];
int l[nmax] , r[nmax];
bool cup(int x)
{
    viz[x] = 1;
    for(auto it : g[x])
    {
        if(!r[it])
        {
            r[it] = x;
            l[x] = it;
            return true;
        }
    }
    for(auto it : g[x])
    {
        if(!viz[r[it]] && cup(r[it]))
        {
            r[it] = x;
            l[x] = it;
            return true;
        }
    }
    return false;
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin >> n >> m >> e;
    for(int i = 1 ; i <= e ; ++i)
    {
        cin >> a >> b;
        g[a].push_back(b);
    }
    int mt = 0;
    while(true)
    {
        bool surplus = 0;
        for(int i = 1 ; i <= n ; ++i) viz[i] = 0;
        for(int i = 1 ; i <= n ; ++i)
        {
            if(!l[i] && cup(i))
            {
                surplus = true;
                mt++;
            }
        }
        if(!surplus) break;
    }
    cout << mt << '\n';
    for(int i = 1 ; i <= n ; ++i) if(l[i]) cout << i << ' ' << l[i] << '\n';
    return 0;
}