Cod sursa(job #2529522)

Utilizator vmnechitaNechita Vlad-Mihai vmnechita Data 23 ianuarie 2020 16:55:33
Problema Cuplaj maxim in graf bipartit Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <iostream>
#include <vector>

using namespace std;

vector < int > v[20001];
int n, m, e, x, y, nr, cuplat[20001];
bool ok, viz[20001];

bool dfs ( int nod );

int main()
{
    int i;

    cin >> n >> m >> e;
    while ( e-- )
    {
        cin >> x >> y;
        v[x].push_back ( y + n );
        v[y+n].push_back ( x );
    }

    ok = 1;
    while ( ok == 1 )
    {
        ok = 0;
        for ( i = 1 ; i <= n + m ; i++ ) viz[i] = 0;
        for ( i = 1 ; i <= n ; i++ ) if ( v[i].empty() == 0 && cuplat[i] == 0 && dfs ( i ) == 1 ) ok = 1;
    }

    //for ( i = 1 ; i <= n ; i++ ) cout << cuplat[i] << ' ';
    for ( i = 1 ; i <= n ; i++ ) if ( cuplat[i] != 0 ) nr++;

    cout << nr << '\n';
    for ( i = 1 ; i <= n ; i++ ) if ( cuplat[i] != 0 ) cout << i << ' ' << cuplat[i] - n << '\n';

    return 0;
}

bool dfs ( int nod )
{
    int i;

    viz[nod] = 1;

    for ( i = 0 ; i < v[nod].size() ; i++ )
    {
        if ( viz[v[nod][i]] == 0 && cuplat[v[nod][i]] == 0 )
        {
            cuplat[nod] = v[nod][i];
            cuplat[v[nod][i]] = nod;
            return 1;
        }
        else if ( viz[cuplat[v[nod][i]]] == 0 && cuplat[v[nod][i]] != nod && dfs ( cuplat[v[nod][i]] ) == 1 )
        {
            cuplat[nod] = v[nod][i];
            cuplat[v[nod][i]] = nod;
            return 1;
        }
    }

    return 0;
}

/*
4 2 5
1 1
1 2
2 2
3 2
4 2


4 2 6
1 1
1 2
2 1
2 2
3 2
4 2


4 3 7
1 1
1 2
2 1
2 2
2 3
3 2
4 2

*/