Cod sursa(job #3216301)

Utilizator Chris_BlackBlaga Cristian Chris_Black Data 15 martie 2024 20:45:24
Problema Cuplaj maxim in graf bipartit Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>
#define pii pair<int, int>
#define ff first
#define ss second
#define vi vector<int>
#define vvi vector<vi>
#define pb push_back
#define eb emplace_back

#define int long long
using namespace std;
const string TASK("cuplaj");
ifstream fin(TASK + ".in");
ofstream fout(TASK + ".out");
#define cin fin
#define cout fout

const int N = 10009;

int n, m, e, l[N], r[N];
bool viz[N];
vvi G(N);

bool DoMatch(int x)
{
    if(viz[x])return false;
    viz[x] = true;

    for(auto y : G[x])
        if(!r[y])
        {
            r[y] = x;
            l[x] = y;
            return true;
        }

    for(auto y : G[x])
        if(DoMatch(r[y]))
        {
            r[y] = x;
            l[x] = y;
            return true;
        }

    return false;
}

int MaxMatching()
{
    int ret = 0;
    bool found_match = true;
    while(found_match)
    {
        found_match = false;
        fill(viz + 1, viz + n + 1, 0);

        for(int i = 1; i <= n; ++i)
            if(!l[i] && DoMatch(i))
        {
            ret ++;
            found_match = true;
        }
    }

    return ret;
}

signed main()
{
    ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);

    cin >> n >> m >> e;

    int x, y;
    for(int i = 1; i <= e; ++i)
    {
        cin >> x >> y;
        G[x].pb(y);
    }

    cout << MaxMatching() << '\n';
    for(int i = 1; i <= n; ++i)
        if(l[i])
            cout << i << ' ' << l[i] << '\n';
    return 0;
}