Cod sursa(job #2976343)

Utilizator Samoila_AlexandruSamoilaAlexandru Samoila_Alexandru Data 8 februarie 2023 23:08:44
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int nMax=1e4+5;

int n, m, e, st[nMax], dr[nMax];
vector<int> g[nMax];
vector<bool> v;

bool cuplaj(int i)
{
    if(v[i])
        return false;

    v[i]=1;

    for(int k : g[i])
        if(!dr[k])
        {
            st[i]=k;
            dr[k]=i;
            return true;
        }

    for(int k : g[i])
        if(cuplaj(dr[k]))
        {
            st[i]=k;
            dr[k]=i;
            return true;
        }

    return false;
}

int main()
{
    ios_base::sync_with_stdio(false);
    fin.tie(0);

    fin>>n>>m>>e;
    int x, y;
    for(int i=0; i<e; i++)
    {
        fin>>x>>y;
        g[x].push_back(y);
    }

    bool ok=true;
    int nrSol=0;

    while(ok)
    {
        ok=false;
        v=vector<bool>(n+1, false);

        for(int i=1; i<=n; i++)
            if(!st[i] && cuplaj(i))
        {
            nrSol++;
            ok=true;
        }
    }

    fout<<nrSol<<'\n';

    for(int i=1; i<=n; i++)
        if(st[i])
        fout<<i<<' '<<st[i]<<'\n';

    fout.close();

    return 0;
}