Cod sursa(job #2939805)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 14 noiembrie 2022 09:55:51
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int maxN = 10005;
int n1, n2, m, used[maxN], l[maxN], r[maxN];
vector <int> G[maxN];

bool pairup(int nod)
{
    if(used[nod])
        return 0;
    used[nod] = 1;
    for(int vecin : G[nod])
    {
        if(!r[vecin])
        {
            l[nod] = vecin;
            r[vecin] = nod;
            return 1;
        }
    }
    for(int vecin : G[nod])
    {
        if(pairup(r[vecin]))
        {
            l[nod] = vecin;
            r[vecin] = nod;
            return 1;
        }
    }
    return 0;
}

int main()
{
    fin >> n1 >> n2 >> m;
    for(int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
    }
    bool changed = 1;
    while(changed)
    {
        changed = 0;
        for(int i = 1; i <= n1; i++)
            used[i] = 0;
        for(int i = 1; i <= n1; i++)
            if(!l[i])
                changed |= pairup(i);
    }
    int ans = 0;
    for(int i = 1; i <= n1; i++)
        if(l[i])
            ans++;
    fout << ans << '\n';
    for(int i = 1; i <= n1; i++)
        if(l[i])
            fout << i << ' ' << l[i] << '\n';
    return 0;
}