Cod sursa(job #1913117)

Utilizator CraiuAndrei Craiu Craiu Data 8 martie 2017 11:48:28
Problema Cuplaj maxim in graf bipartit Scor 28
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
///O(sqrt(n + m) * k)
#include <bits/stdc++.h>

using namespace std;

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

const int nMax = 10005;
int n, m, k, ans;
int st[nMax], dr[nMax];
bool viz[nMax];
vector <int> L[nMax];

inline void Citeste()
{
    int i, x, y;
    fin >> n >> m >> k;
    for(i = 1; i <= k; i++)
    {
        fin >> x >> y;
        L[x].push_back(y);
    }
}

inline bool Cuplaj(int nod)
{
    if(viz[nod]) return false;
    viz[nod] = true;
    for(auto it : L[nod])
        if(!dr[it])
        {
            st[nod] = it;
            dr[it] = nod;
            return true;
        }
    for(auto it : L[nod])
        if(Cuplaj(it))
        {
            st[nod] = it;
            dr[it] = nod;
            return true;
        }
    return false;
}

inline void Rezolva()
{
    int i;
    bool gata = false;
    while(!gata)
    {
        gata = 1;
        for(i = 1; i <= n; i++)
            viz[i] = 0;
        for(i = 1; i <= n; i++)
            if(!st[i] && Cuplaj(i))
            {
                ans++;
                gata = 0;
            }
    }
    fout << ans << "\n";
    for(i = 1; i <= n; i++)
        if(st[i])
            fout << i << " " << st[i] << "\n";
}

int main()
{
    Citeste();
    Rezolva();
    return 0;
}