Cod sursa(job #3225123)

Utilizator TeodoraMaria123Serban Teodora Maria TeodoraMaria123 Data 16 aprilie 2024 21:53:33
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <bits/stdc++.h>

using namespace std;

#define MAX_N 10000

vector <int> matchLeft, matchRight;
vector <vector <int> > graph;
bitset <MAX_N + 1> viz;

int n, m, e, ans;

bool pairUp(int node)
{
    if(viz[node] == 1)
        return 0;

    viz[node] = 1;

    for(int x : graph[node])
    {
        if(!matchLeft[x - n])
        {
            ans ++;
            matchLeft[x - n] = node;
            matchRight[node] = x - n;
            return 1;
        }
    }

    for(int x : graph[node])
    {
        if(matchLeft[x - n] != node  &&  pairUp(matchLeft[x - n]))
        {
            matchLeft[x - n] = node;
            matchRight[node] = x - n;
            return 1;
        }
    }

    return 0;
}

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

    freopen("cuplaj.in", "r", stdin);
    freopen("cuplaj.out", "w", stdout);

    cin >> n >> m >> e;
    graph.resize(n + 1);
    matchLeft.resize(m + 1, 0);
    matchRight.resize(n + 1, 0);

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

    bool change = 1;
    while(change)
    {
        change = 0;
        for(int j = 0; j <= n; j ++)
            viz[j] = 0;
        int copyAns = ans;
        for(int i = 1; i <= n; i ++)
            if(!matchRight[i])
                pairUp(i);
        change = (copyAns < ans);
    }


    cout << ans << "\n";
    for(int i = 1; i <= m; i++)
        if(matchLeft[i])
            cout << matchLeft[i] << " " << i << "\n";
    return 0;
}