Cod sursa(job #1548971)

Utilizator tudormaximTudor Maxim tudormaxim Data 11 decembrie 2015 18:49:24
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
const int nmax = 10005;
vector <int> g[nmax];
int st[nmax], dr[nmax];
bool viz[nmax], ok=true;

bool cuplaj(int dad)
{
    int i, son;
    if(viz[dad]) return false;
    viz[dad]=true;
    for(i=0; i<g[dad].size(); i++)
    {
        son=g[dad][i];
        if(dr[son]==0)
        {
            st[dad]=son;
            dr[son]=dad;
            return true;
        }
        if(cuplaj(dr[son]))
        {
            st[dad]=son;
            dr[son]=dad;
            return true;
        }
    }
    return false;
}

int main()
{
    ifstream fin ("cuplaj.in");
    ofstream fout ("cuplaj.out");
    ios_base::sync_with_stdio(false);
    int n, m, i, x, y, t, nr=0;
    fin >> n >> m >> t;
    for(i=1; i<=t; i++)
    {
        fin >> x >> y;
        g[x].push_back(y);
    }
    while(ok)
    {
        ok=false;
        for(i=1; i<=n; i++)
            viz[i]=false;
        for(i=1; i<=n; i++)
            if(st[i]==0 && cuplaj(i)) ok=true;
    }
    for(i=1; i<=n; i++)
        if(st[i]) nr++;
    fout << nr << "\n";
    for(i=1; i<=n; i++)
        if(st[i]) fout << i << " " << st[i] << "\n";
    fin.close();
    fout.close();
    return 0;
}